递归函数实现快速排序算法
#include <stdio.h>
#include <stdlib.h>
int QKPass(int r[],int low,int high)
{
int x;
x = r[low];
while(low<high)
{
while(low<high && r[high]>=x)
{
high--;
}
if(low<high)
{
r[low] = r[high];
low++;
}
while(low<high && r[low]<x)
{
low++;
}
if(low<high)
{
r[high] = r[low];
high--;
}
}
r[low]=x;
return low;
}
void QKSort(int r[],int low,int high)
{
int pos;
if(low<high)
{
pos = QKPass(r,low,high);
QKSort(r,low,pos-1);
QKSort(r,pos+1,high);
}
}
int* QuickSort(int *array,int begin,int end)
{
if(begin>end)
return NULL;//递归函数返回条件
int x = array[begin];
int i = begin,j = end;
int temp;
while(i != j)
{
while((array[j] >= x)&&(j > i))
j--; //从最右侧开始寻找比X小的数
while((array[i] <= x)&&(j > i))
i++; //从最左侧开始寻找比X大的数
if(j>i)
{
temp = array[i];//两个数交换
array[i] = array[j];
array[j] = temp;
}
}
array[begin] = array[j];
array[j] = x;
//此时 i==j ,完成左侧数都比X小,右侧数比X大
QuickSort(array,begin,i-1);//递归调用,左侧再排序
QuickSort(array,i+1,end);//递归调用,右侧再排序
return array;
}
/******************************************/
int main()
{
int i;
int a[] = {4,1,2,3,4,5,6,9,8,7,5,54,76,89};
QKSort(a,0,13);
for(i=0;i<14;i++)
printf("%d ",a[i]);
return 0;
}