1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| #include<iostream> using namespace std; #define MAXSIZE 100 #define Status bool #define KeyType int #define InfoType int typedef struct{ KeyType key; InfoType info; }ElemType; typedef struct{ ElemType r[MAXSIZE+1]; int length; }SqList;
int Partition(SqList &L, int low, int high);
int AdvancedPartition(SqList &L, int low, int high); Status QuickSort(SqList &L); Status QSort(SqList &L, int low,int high); int main() { SqList L; cout << "Input the length of sequence: "; cin >> L.length; for(int i=0;i<L.length;i++){ cin >> L.r[i+1].key; } QuickSort(L); cout << "After quick sorting output the sequence:\n"; for(int i=0;i<L.length;i++){ cout << L.r[i+1].key << " "; } cout << endl; return 0; } Status QuickSort(SqList &L) { QSort(L, 1, L.length); return true; } Status QSort(SqList &L, int low,int high) { if(low < high){ int piv = AdvancedPartition(L, low, high); QSort(L, low, piv-1); QSort(L, piv+1, high); } return true; } int Partition(SqList &L, int low, int high) { L.r[0] = L.r[low]; int piv = L.r[low].key; while(low < high) { while(low<high && L.r[high].key >= piv) high--; L.r[low] = L.r[high]; while(low<high && L.r[low].key <= piv) low++; L.r[high] = L.r[low]; } L.r[low] = L.r[0]; return low; } int AdvancedPartition(SqList &L, int low, int high) { int piv = 0, inpiv = 0; int maxv = L.r[low].key > L.r[high].key?low:high; int minv = low + high - maxv; int midv = (low+high)/2; if(L.r[midv].key < L.r[minv].key) inpiv = minv; else if(L.r[midv].key > L.r[maxv].key) inpiv = maxv; else inpiv = midv; L.r[0] = L.r[inpiv]; piv = L.r[inpiv].key; if(inpiv != low) L.r[inpiv] = L.r[low]; while(low < high) { while(low<high && L.r[high].key >= piv) high--; L.r[low] = L.r[high]; while(low<high && L.r[low].key <= piv) low++; L.r[high] = L.r[low]; } L.r[low] = L.r[0]; return low; }
|