您好,登錄后才能下訂單哦!
這篇文章主要介紹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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。