快速排序(假设我们要排成升序)的思想是:
取第一个值为中间值,然后遍历(虽然是从数组两边同时遍历,但是时间复杂度依旧是O(n)),把比中间值小的放在中间值左边,把比中间值大的放在中间值右边。
然后两边继续刚才的循环,其实也就是递归。
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
void sort_(int *,int,int);//排序
int findpos(int*,int,int);//找到第一个元素排序后(其实还没排),应该所在的位置
int main(void)
{
int i;
int a[5] = {5,4,3,2,-1};
sort_(a,0,4);//将下表0~4的元素进行排列
for(i=0;i<5;i++)
{
printf("%d ",a[i]);
}
return 0;
}
void sort_(int *p,int low,int high)
{
if(low<high)
{
int pos = findpos(p,low,high);
sort_(p,low,pos-1);//对中间值两边的数组继续进行刚刚的操作
sort_(p,pos+1,high);
}
}
int findpos(int*p,int low,int high)
{
int val = p[low];
while(low<high)
{
while(low<high && val<= p[high])
{
high--;
}
p[low] = p[high];
while(low<high && val>= p[low])
{
low++;
}
p[high] = p[low];
}
p[low] = val;
return low;
}