巧妙利用快速排序法的原理求一个数组中的第10大元素

//快速排序法
int QuickSort_process3(int *a, int low, int high)
{
	int l, h, temp;
	l = low;
	h = high;
	temp = a[low];
	while (l < h){
		while (l< h&&a[h] >= temp)
			--h;
		if (l < h)
			a[l] = a[h];
		while (l < h&&a[l] < temp)
			++l;
		if (l < h)
			a[h] = a[l];
	}
	a[h] = temp;
	return h;
}

void QuickSort3(int *a, int low,int high)
{
	int pos;
	if (low < high){
		pos = QuickSort_process3(a,low,high);
		QuickSort3(a,low,pos-1);
		QuickSort3(a,pos+1,high);
	}
}

int getTop_N_Numbers(int *a,int n)
{
	int pos, curpos, e;
	do{
		printf("Please input a numbers(less than %d and bigger than 0).\n", n);
		scanf("%d",&e);
	} while (!(e<=n&&e>=1));
	pos = n - e;/*在一个从小到大排序的数组中,最大第e个数的下标恰好是n-e*/
	curpos = QuickSort_process3(a, 0, n - 1);/*一趟快排结束时,肯定会有一个已经确定了位置的数,返回它的下标*/
	while (1){
		if (curpos == pos){/*当要找的第几最大的数的位子已经确定后,说明,比它还要大的数也已经确定了,就不再排序了,直接返回*/
			break;
		}
		else if (curpos < pos){/*在后半部找*/
			curpos = QuickSort_process3(a,curpos+1,n-1);
		}
		else{/*在前半部分找*/
			curpos = QuickSort_process3(a,0,curpos-1);
		}
	}
	return pos;	
}

void show_TopN_numbers(int *a,int n)
{
	int k = getTop_N_Numbers(a, n);
	int i;
	printf("The Top %d numbers are :\n",n-k);
	for (i = k; i < n; ++i)
		printf("%d ",a[i]);
	printf("\n");
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值