快速排序算法: #include <iostream> typedef int ElementType; const int Cutoff = 3; void InsetionSort(ElementType A[], int N) //插入排序,如果排序数据个数较少,可以采用 { int j,P; ElementType Tmp; for (P = 1; P < N; P++) { Tmp = A[P]; for(j = P;j > 0 && A[j-1] < Tmp; j--) //将数据右移。 A[j] = A[j-1]; A[j] = Tmp; } } void Swap(ElementType *a, ElementType *b) //pass-by-reference按地址传 { ElementType temp; temp = *a; *a = *b; *b = temp; } ElementType Median3(ElementType A[], int Left, int Right) //取枢纽元 { int Center = (Left + Right)/2; if(A[Left] > A[Center]) Swap(&A[Left], &A[Center]); if(A[Left] > A[Right]) Swap(&A[Left], &A[Right]); if(A[Center] > A[Right]) Swap(&A[Center], &A[Right]); Swap(&A[Center], &A[Right - 1]); //存储枢纽元 return A[Right - 1]; //返回枢纽元 } void Qsort(ElementType A[], int Left, int Right) { int i,j; ElementType Pivot; if(Left + Cutoff <= Right) { Pivot = Median3(A, Left, Right); i = Left; j =Right - 1; for(;;) { while(A[++i] < Pivot){} //如果数据一直小于枢纽元,则i右移,停下时i指向第一个大于枢纽元的数的位置 while(A[--j] > Pivot){} //如果数据一直大于枢纽元,则j左移,停下时j指向第一个小于枢纽元的数的位置 if(i < j) Swap(&A[i], &A[j]); //如果i在j的左边,则交换2个元素, else break; } Swap(&A[i], &A[Right - 1]); //交换i处的数据和枢纽元,这样枢纽元左边都是小于它的数,右边则全部是大于它的数 Qsort(A, Left, i -1); //对左边的数递归调用快排 Qsort(A, i + 1, Right); } else InsetionSort(A + Left, Right - Left + 1); //如果数据量较小,可以采用插入排序 } int main() { ElementType A[10] = {12,2,42,52,25,67,6,42,9,1}; int i; Qsort(A,0,9); std::cout << "numbers sorted:/n" << std::endl; for (i = 0; i < 10; i++) { std::cout << A[i] << " "; } std::cout << std::endl; system("pause"); return 0; } 转载: //快速排序算法 #include <iostream> #include <cstdlib> #include <ctime> using namespace std; //快速排序 int Partition(int num[],int i,int j) //调用Partition(num,low,high)时,对num[low...high]做划分,并返回基准记录的位置 { int pivot=num[i]; //用区间的第1个记录作为基准 while(i<j) //从区间两端交替向中间扫描,直至i=j为止 { while(i<j && num[j]>=pivot) //pivot相当于在位置i上 j--; //从右向左扫描,查找第1个关键字小于pivot的记录num[j] if(i<j) //表示找到的num[j]的关键字<pivot num[i++]=num[j]; //相当于交换num[i]和num[j],交换后i指针加1 while(i<j && num[i]<=pivot) //pivot相当于在位置j上 i++; //从左向右扫描,查找第1个关键字大于pivot的记录num[i] if(i<j) //表示找到了num[i],使num[i]>pivot num[j--]=num[i]; //相当于交换num[i]和num[j],交换后j指针减1 }//end while num[i]=pivot; //基准记录已被最后定位 return i; } void Quicksort(int num[],int low,int high) { int pivotpos; //划分后的基准记录的位置 if(low<high) //仅当区间长度大于1时才须排序 { pivotpos=Partition(num,low,high); //对num[low..high]做划分 Quicksort(num,low,pivotpos-1); //对左区间递归排序 //for(int i=low;i<=pivotpos-1;i++) //追踪左区间的排序情况 //cout<<num[i]<<" "; //cout<<endl; Quicksort(num,pivotpos+1,high); //对右区间递归排序 //for(i=pivotpos+1;i<=high;i++) //追踪右区间的排序情况 //cout<<num[i]<<" "; //cout<<endl; } } int main() { srand((unsigned)time(0)); //随机生成数据算法 int num[100]; for(int i=0;i<100;++i) num[i] = rand()%1000; cout << "随机生成的原始数据 :"; for(i=0;i<100;++i) { if(0 == i%10) cout<<endl; cout<<num[i]<<" "; } Quicksort(num,0,99); cout << endl << endl << "排序后的数据:"; for(i=0;i<100;++i) { if (0 == i%10) cout<<endl; cout <<num[i]<<" "; } return 0; }