快速排序算法的实现关键就是我们选的基准的位置!然后程序就是个递归调用,数组和链表的实现上还是有很大的差别的。
#include "stdio.h"
//快速排序,核心是定位和递归(数组实现)
void swap(int &a,int &b)
{ //传地址交换
int temp = a;
a = b;
b =temp;
}
//这个交换方法用到这里是不行的
void swap0(int a,int b)
{ //传值交换
int temp = a;
a = b;
b =temp;
}
int Partition(int *list,int low,int high)
{
int pivotKey;
pivotKey = list[low];
while(low<high)
{
while(low<high&&list[high]>=pivotKey)
{
high--;
}
swap(list[low],list[high]);
while(low<high&&list[low]<=pivotKey)
{
low++;
}
swap(list[low],list[high]);
}
return low;
}
void Qsort(int *list,int low,int high)
{
int pivot;
if(low<high)
{
pivot =Partition(list,low,high);
Qsort(list,low,pivot-1);
Qsort(list,pivot+1,high);
}
}
void Quick_Sort(int *list,int count)
{
Qsort(list,0,count-1);
}
void Show(int *a,int n)
{
for(int i=0;i<n-1;i++)
{
printf("%d\t",a[i]);
}
}
int main()
{
int a[] ={0,2,5,8,10,16,1};
//int Start = 0;
int n =sizeof(a)/sizeof(a[0]);
Quick_Sort(a,n);
Show(a,n);
return 0;
}