搞了一个下午,用两种方法partion,一种分成两部分,一种分成三部分,分成三部分的用的上回写的荷兰国旗问题的思想,很给力,没事多写写,下面写个红黑树和二叉查找树,B树知道就行了。
#include<iostream> #include<stdio.h> #include<time.h> using namespace std; void swap(int &a,int &b) { int c=a; a=b; b=c; } void display(int a[],int len) { cout<<"a[]的大小"<<sizeof(a)<<endl; for(int i=0;i<len;i++) { cout<<a[i]<<" "; } cout<<endl; } int partion(int *a,int low,int high) { int cur=low; int key=a[low]; swap(a[low],a[high]); int index=low; while(cur<high) { if(a[cur]<key) { swap(a[index++],a[cur]); } cur++; } swap(a[index],a[high]); return index; } void quicksort(int *a,int low,int high) { if(low>=high) return; int mid=partion(a,low,high); quicksort(a,low,mid-1); quicksort(a,mid+1,high); } //下面以a[low]为枢轴,进行划分成三分,返回两边的临界值,利用引用; void partion2(int a[],int low,int high,int &e1,int &e2) { int key=a[low]; int cur=low; int beg=low; int end=high; while(cur<=high) { if(a[cur]<key) { swap(a[beg],a[cur]); beg++; cur++; } else if(a[cur]=key) { cur++; } else { swap(a[cur],a[end]); end--; } } e1=beg-1; e2=end+1; } void quicksort2(int a[],int low,int high) { int e1; int e2; if(low>=high) return; partion2(a,low,high,e1,e2); quicksort2(a,low,e1); quicksort(a,e2,high); } int main() { int len=78;//随机数的个数 srand((unsigned)time(NULL)); int a[1000]; for(int i=0;i<len;i++) { a[i]=rand()%1000; } clock_t beg,end; beg=clock(); quicksort2(a,0,len-1); end=clock(); double duration=(double)(end-beg)/CLOCKS_PER_SEC; display(a,len); cout<<"用的总时间"<<duration<<endl; system("pause"); return 0; }