//快速排序
# include<stdio.h>//时间复杂度 O(nlogn) 不稳定
void QuickSort(int a[], int n){
int low, high, p, t;
if(n < 2)//只有一个数,不用交换
return;
p = a[n/2]; //p取数组a的中间的数
for(low = 0, high = n-1;; low++, high--){ //从p的两边开始排序
while(p > a[low]) //将小于p的数放在左边,大于p的数放在p的右边
low++;
while(p < a[high])
high--;
if(low >= high) break;
t = a[low]; //如果p左边的数比p右边的那个数大,把p左右两边数交换一下
a[low] = a[high];
a[high] = t;
}
QuickSort(a, low); //第一个递归调用处理数组的前部分,a对应的是数组的首地址,low是指对应的元素个数
QuickSort(a+low, n-low);//第二个递归调用处理数组后部分,a + low指的当然是首地址加偏移地址,n-low就是p后面剩下的元素个数
}
int main(){
int n;
printf("请输入你要排序的数的个数:");
scanf("%d", &n);
int *a = new int[n];//申请一个整型变量空间,没有赋初值,并定义一个整型指针a指向该地址空间
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
QuickSort(a, n);
printf("排序后:");
for(int j = 0; j < n; j++)
printf("%6d", a[j]);
delete []a;//回收数组a的空间
return 0;
}