这篇文章主要介绍c++怎么实现对输入数组进行快速排序,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
直接上代码
#include "stdafx.h" #include <iostream> #include <string> #include <vector> using namespace std; void quickSort(vector<int> &a, int, int); void swap(int &a, int&b); vector<string> split(string s, string seperator); int main() { string str; cout << "please input your array: " << endl; getline(cin, str); vector<string> strs = split(str, " "); cout << "The original array is " << endl; for (unsigned int i = 0; i < strs.size(); i++) { cout << strs[i] << " "; } cout << endl; vector<int> array(strs.size()); for (unsigned int i = 0; i < strs.size(); i++) { array[i] = atoi(strs[i].c_str()); } int len = array.size(); cout << "The ordered array is " << endl; quickSort(array, 0, len-1); for (int i = 0; i < len; i++) { cout << array[i] << " "; } cout << endl; system("pause"); return 0; } void quickSort(vector<int> &a, int start, int base) { if (start >= base) { return; } int i = start, j = start; int temp = a[base]; for (;j<base;j++) { if (a[j]<=temp) { swap(a[i], a[j]); i++; } } if (a[i] > a[base]) { swap(a[i], a[base]); } quickSort(a, start, i - 1); quickSort(a, i + 1, base); } void swap(int &a, int&b) { if (a == b) { } else { a = a + b; b = a - b; a = a - b; } } vector<string> split(string s, const string pattern) { string::size_type pos; vector<string> result; s += pattern; unsigned int size = s.size(); for (unsigned int i = 0; i < size; i++) { pos = s.find(pattern, i); if (pos < size) { string str = s.substr(i, pos - i); if (!str.empty()){ result.push_back(str); } i = pos + pattern.size() - 1; } } return result; }
以上是“c++怎么实现对输入数组进行快速排序”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。