排序算法-----快速排序:
快速排序的算法思想:递归的排序,每次将起始下标的数组元素值作为基数,然后先从末尾寻找比基数小的数,接着从起始位置寻找比基数大的数,交换位置之后,在起始下标x++的过程中与末尾下标y–的过程中,x==y的时候,将基数放入其中,接着就是递归的思想.
观察下图,根据上述思想,自行移动。元素2拿出了。
代码如下:
#include <stdio.h>
void quicksort(int *a, int start, int end)//参数:数组,起始下标,末尾下标
{
if(start > end) //递归出口
{
return;//停止递归
}
int x = start;
int y = end;
int base = a[start]; //base为基数,将数组起始元素值作为基数
while(x < y) //起始位置与末尾位置循环变化过程中的关系
{
while(a[y]>base && x<y) //先从后面寻找小的数
{
y--;
}
if(x < y)
{
a[x++] = a[y];
}
while(a[x]<base && x<y) //接着从前面寻找大的数
{
x++;
}
if(x<y)
{
a[y--] = a[x];
}
}
a[x] = base; //这里表示x==y了,最后将基数放在空白的下标位置
quicksort(a, start, x-1);//基数左边数循环递归排序
quicksort(a, y+1, end);//基数右边数循环递归排序
}
int main()
{
int arry[]={12,10,21,0,6,7,18,16,30,99,85,76,24,31,2};
int length = sizeof(arry)/sizeof(int);
printf("排序前: ");
for(int i=0; i<length; i++)
{
printf("%d ", arry[i]);
}
quicksort(arry, 0, length-1);
printf("\n排序后: ");
for(int i=0; i<length; i++)
{
printf("%d ", arry[i]);
}
return 0;
}
程序运行如下: