以下为一趟快速排序(帮助理解):
#include <stdio.h>#define N 10void Partition_Sort(int A[],int low,int high){ int pivot=A[low]; while(low<high) { while(low<high&&A[high]>=pivot) //将比枢轴值小的元素移动到左 { --high; A[low]=A[high]; } while(low<high&&A[low]<=pivot) //将比枢轴值大的元素移动到右 { ++low; A[high]=A[low]; } } A[low]=pivot; //枢轴元素存放到最终位置}int main() { int m = 0; int B[N] = {4,5,6,1,2,3,7,8,9}; printf("=============================/n/n"); printf("排序前的数据是:/n4 5 6 1 2 3 7 8 9/n"); Partition_Sort(B,0,9); printf("一趟快速排序后的结果是:/n"); for(m=1; m<N;m++) { printf(" %d ", B[m]); } printf("/n/n=============================/n/n"); return 0; }用递归完成整个排序过程:
#include <stdio.h>#define N 10void Quick_Sort(int A[],int low,int high){ int i=low; int j=high; int pivot = A[i]; //将low记录为枢轴元素 if(low<high) //跳出循环条件 { while(i<j) { while((A[j]>= pivot)&&(i<j)) //比枢轴元素大的放在其后 { j--; } A[i]=A[j]; while((A[i]<=pivot)&&(i<j)) { i++; } A[j]= A[i]; } A[i]=pivot; //确定好枢轴元素的位置 Quick_Sort(A,low,i-1); //递归 Quick_Sort(A,j+1,high); } else { return; }}int main() { int m = 0; int time=N; int B[N] = {4,5,6,1,2,3,7,8,9}; printf("=============================/n/n"); printf("排序前的数据是:/n4 5 6 1 2 3 7 8 9/n"); Quick_Sort(B,0,9); printf("排序后的结果是:/n"); for(m=1; m<N;m++) { printf(" %d ", B[m]); } printf("/n/n=============================/n/n"); return 0; }新闻热点
疑难解答