人这玩意果然是三分钟热度……废话就不写了,一步步来吧。
快速排序:worstcase O(n2)
expected time complexity:O(nlgn)
快排的思路:分治法,分解—>解决(递归)—>合并(不需要,原址排序)
伪代码:
quicksort(A,p,r) if p<r q=partition(A,p,r); quicksort(A,p,q-1); quicksort(A,q+1;r);
partition(A,p,r) q=A[r]; i=p-1; for j from p to r-1 if A[j]<=q i++; exchange A[i] with A[j]; exchange A[i+1] with A[r] return i+1
注意:quicksort调用时分情况为p—q-1与q+1—r;A[q]不必加入(否则会被多次利用重复出错)
oj 1032:quicksort
代码如下
#include<iostream> using namespace std; int partition(int a[],int p,int r) { int q=a[r]; int s=p-1; for (int i=p;i<r;i++) { if (a[i]<=q) { s++; int temp=a[s]; a[s]=a[i]; a[i]=temp; } } int temp=a[r]; a[r]=a[s+1]; a[s+1]=temp; return s+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[100]; int n; 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]; if (i!=n-1) cout<<" "; } cout<<endl; } return 0; }
剩下的证明啊分析啊下次吧……