快速排序算法是C/C++库所使用的标准排序算法,用于对中等长度的数组进行排序。快速排序算法的原理是通过找出一个数,使得这个数左边的所有数字都小于它,右边的所有数字都大于它。通过不断地递归而排序整个数组。快速排序算法的实现如下:
代码块
#include <stdio.h>
int sort(int a[] , int low , int high) {
int temp = a[low];
swap(&temp,&a[(low+high)/2]);
while (low<high) {
while(a[high]>=temp && high > low) {
high--;
}
if(high==low) break;
a[low] = a[high];
low++;
while(a[low]<=temp && low < high) {
low++;
}
if(high==low) break;
a[high] = a[low];
high--;
}
a[high] = temp;
return high;
}
void quicksort (int a[] , int low , int high) {
if(low>=high) return;
int middle = sort(a,low,high);
quicksort(a,low,middle);
quicksort(a,middle+1,high);
}
void swap (int *x , int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void printarray (int a[],int length) {
int i;
for(i=0;i<length;i++) {
printf("%d ",a[i]);
}
printf("\n");
}
void main() {
int a[20] = {1,89,53,21,33,76,654,10000,2,5,86,443,231,55,23,67,11,90,100,7};
quicksort(a,0,19);
printarray(a,20);
}