#include <iostream> using namespace std; void swap(int &a,int &b){ int temp; temp = a; a = b; b = temp; } int partition(int A[],int p ,int r){ int x = A[r]; int i = p - 1; for(int j = p;j < r;j++) if(A[j] <= x){ i++; swap(A[i],A[j]); } swap(A[i + 1],A[r]); return i + 1; } void quicksort(int A[],int p ,int r){ if(p < r){ int q = partition(A,p,r); quicksort(A,p,q - 1); quicksort(A,q + 1,r); } } int main() { int a[10]; for(int i = 1; i <= 10;i++) cin >> a[i]; quicksort(a,1,10); for(int i = 1; i <= 10;i++) cout << a[i] << " "; system("pause"); return 0; }
随机化的快速排序
#include <iostream> #include <cstdlib> using namespace std; void swap(int &a,int &b){ int temp; temp = a; a = b; b = temp; } int rand(int p,int r){ int size = r - p + 1; return p + rand() % size; } int partition(int A[],int p ,int r){ swap(A[rand(p,r)],A[r]); int x = A[r]; int i = p - 1; for(int j = p;j < r;j++) if(A[j] <= x){ i++; swap(A[i],A[j]); } swap(A[i + 1],A[r]); return i + 1; } void quicksort(int A[],int p ,int r){ if(p < r){ int q = partition(A,p,r); quicksort(A,p,q - 1); quicksort(A,q + 1,r); } } int main() { int a[10]; for(int i = 1; i <= 10;i++) cin >> a[i]; quicksort(a,1,10); for(int i = 1; i <= 10;i++) cout << a[i] << " "; system("pause"); return 0; }
#include<iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; void swap(int &a,int &b){ a = a ^ b; b = a ^ b; a = a ^ b; } int partition(int *a,int p,int r){ int rot = a[p]; int i = p,j = r; while(i < j){ while(a[j] >= rot && i < j) j--; a[i] = a[j]; while(a[i] <= rot && i < j) i++; a[j] = a[i]; } a[i] = rot; return i; } void quickSort(int *a,int p,int r){ if(p < r){ int q = partition(a,p,r); quickSort(a,p,q - 1); quickSort(a,q + 1,r); } } int main(){ int n,a[100]; while(cin >> n) { for(int i = 0;i < n; i++) cin >> a[i]; quickSort(a,0,n - 1); for(int i = 0;i < n; i++) cout << a[i] << " "; } return 0; }