標籤:交換 using 快速排序 sort end 快排 void IV key
#include <iostream>using namespace std;template <class T>void qSort(T *a, int left, int right);// 快速排序template <class T>void sW(T *a, T *b);int main(){ int a[] = {3, 4, 5, 12, -1, -33, 90, -44, -23, 100, -1111, -9}; int len = sizeof(a)/sizeof(int); cout << *(a+1); cout << "未經處理資料:" << endl; for(int i = 0; i <len; ++i ) cout << a[i] <<"、"; cout << endl; qSort(a, 0, len-1); cout << "快排後資料:" << endl; for(int i = 0; i <len; ++i ) cout << a[i] <<"、";}template <class T>void qSort(T *a, int left, int right){ const int len = right; while(left < right){ while( *(a+left) < *(a+right) && left < right ) --right; // 以輸入隊列的第一個數為Key,自右向左尋找比key小的數,當前數不比key小則--right sW(a+left, a+right); while( *(a+left) < *(a+right) && left < right ) ++left; // 從左向右找比key大的數,找到後交換 sW(a+left, a+right); qSort(a, 0, left-1); qSort(a, left+1, len); }}template <class T>void sW(T *a, T *b){ T temp; temp = *a; *a = *b; *b = temp;}
快速排序C++代碼