利用C语言实现快速排序
一、排序思想
(1)选择数组元素e(作为“分割元素”),然后重新排列数组使得元素从1到i-1都是小于等于e的,元素i包含e,元素i+1到n都是大于等于e的。
(2)递归采用快速排序方法,对1到i-1的元素进行排序。
(3)递归采用快速排序方法,对i到n的元素进行排序。
二、代码实现
#define N 10 //定义宏,以排序个数10 为例
void quicksort(int a[],int low ,int high); //快速排序函数
int split(int a[],int low ,int high); //分割函数
int a[N],i;
printf("enter %d numbers to be sorted ",N);//传入排序的数组
for(i =0;i<N;i++){
scanf("%d",&a[i]);
}
quicksort(a,0,N-1);
printf("sorted order: ");
for(i =0;i<N;i++){
printf("%d",a[i]);
}
printf("\n");
return 0;
}
void quicksort(int a[],int low ,int high){
int middle;
if(low>=high) return;
middle = split(a,low,high);
quicksort(a,low,middle-1);
quicksort(a,middle+1,high);
}
int split(int a[],int low ,int high){
int part_element = a[low];
for(;;){
while(low<high && a[low] <= part_element)
low++;
if(low >= high) break;
a[high--] = a[low];
}
a[high] = part_element;
return high;
}