您的位置:首页 > 其它

POJ 2388 Who's in the Middle 快排解法

2014-06-12 20:29 429 查看
又是一题快速排序的题目,活用快排求某个位置的数。

这次完善一下自己的基础,把快排代码规范化和增加一个random算法,进一步确保不会出现最坏情况。

思路和前一道题差不多,不过是求第k个数了,这里的第k个数是中序数。

花了点时候整理下代码,果然变得十分工整了。

#include <cstdio>
#include <stdlib.h>
#include <algorithm>
#include <time.h>
using namespace std;
const int SIZE = 10000;
int arr[SIZE];

int partition(int *arr, int low, int up)
{
	for (int j = low; j < up; j++)
		if (arr[j] < arr[up]) 
			swap(arr[low++], arr[j]);

	swap(arr[low], arr[up]);
	return low;
}

int selectK_1(int *arr, int low, int up, int k)
{
	int r = rand() % (up - low + 1) + low;
	swap(arr[r], arr[up]);

	int m = partition(arr, low, up);
	int lowerParts = m - low + 1;

	if (lowerParts == k) return arr[m];
	if (k < lowerParts) return selectK_1(arr, low, m-1, k);
	return selectK_1(arr, m+1, up, k - lowerParts);
}

int main()
{
	srand((int)time(NULL));
	int N;
	while (~scanf("%d", &N))
	{
		for (int i = 0; i < N; i++)
		{
			scanf("%d", &arr[i]);
		}
		printf("%d\n", selectK_1(arr, 0, N-1, (N>>1)+1));
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: