为什么快速排序第二个while循环内仍然要判断 low 小于 high 以及为什么要从high减减开始.

每次循环结束后输出一下返回的位置信息 pivot
你就发现一趟后返回的位置比实际的要大1
就是因为第二层内的while没有low < high的判断的约束,导致low和high的值错乱

#include<stdio.h>

int count=0;  //全局变量 记录进行了多少趟快速排序 


void print(int a[],int n){
	for(int i=0;i<n;i++){
		printf("%d ",a[i]);
	}
	printf("\n");
}

int partition (int a[],int low,int high){
	count++;
	int lengh =  5; 				  //记录排序数组的长度 
	printf("第%d次快速遍历前 \n",count); 
	print(a,lengh);
	int temp = a[low];
	while(low < high){
		while(a[low] <= a[high])  high--;   //high--开始是因为temp保存了a[low]的值,如果从low++开始,a[high]原本的值会被覆盖
		a[low] = a[high];
		while(a[low] <= a[high])  low++;
		a[high] = a[low];
	}
	a[low] = temp;
	printf("第%d次快速遍历后 \n",count); 
	print(a,lengh);
	
	return low;
} 


int sort(int a[],int low,int high){
	if(low < high){
		int pivot = partition(a,low,high);
		printf("pivot=%d \n\n ",pivot);
		sort(a,low,pivot-1);
		sort(a,pivot+1,high);
	}
}

int main(){
	/*
	int a[10]={3,1,2,4,5,6,9,7,10,8};
	print(a,10); 
	sort(a,0,9);
	print(a,10); 
	*/
	int a[5]={3,1,2,5,4};
	sort(a,0,4);
	printf("\n排序结束后\n");
	print(a,5); 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值