C语言实现快速排序算法

快速排序

思想:采用分治的排序策略,随机取一基准值,分别从数组两侧与基准值比较,以升序排列为例,若左边出现比基准值大的数,则停止取数,记录当前元素下标,开始从右侧取数与基准值相比较,若出现比基准值小的数,停止,将左侧与右侧数做交换……以此类推,当左边指针与右边指针重叠时,停止本次循环。

#include

int a[30] = {98,4,6,12,32,34,65,67,23,222,333,444,531,123,111,221,334,246,765,2,9,14,15,36,64,74,42,45,109,47};

int fastSort(int *a,int low,int high){
	int basic = a[high];
	int i = low;
	int j = high;
	int tmp;
	int index;
	
	if( i >= j){
		return 0;
	}
	
	while( i != j){
		while(a[i] < basic) {
			i++;
		}
		
		while(a[j] > basic){
			j--;
		}		

		tmp = a[i];
		a[i] = a[j];
		a[j] = tmp;

	}			

	index = i;
	
	fastSort(a,low,index-1);
	fastSort(a,index+1,high);
	return index;
}

int main(void){
	int low = 0;
	int high = 29;
	int index;
	index = fastSort(a,low,high);
	
	for(low=0;low<=29;low++){
		printf("%d ",a[low]);
	}

} 

你可能感兴趣的:(快速排序,排序算法)