码迷,mamicode.com
首页 > 其他好文 > 详细

O(n)时间复杂度求最小的k个数和第k小的数

时间:2015-04-07 00:47:48      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:partition

//思路:使用快速排序的patition函数来进行处理 时间复杂度为O(n)
#include<iostream>
#include<cassert>
using namespace std;

int partition(int *ar, int len, int low, int high)
{
	int temp = ar[low];

	while(low < high)
	{
		while(low < high && temp < ar[high])
		{
			high--;
		}
		if(low == high)
		{
			break;
		}
		else
		{
			ar[low] = ar[high];
		}

		while(low < high && temp > ar[low])
		{
			low++;
		}
		if(low == high)
		{
			break;
		}
		else
		{
			ar[high] = ar[low];
		}
	}
	ar[low] = temp;
	return low;
}

int findkmin(int *ar, int len, int k)//寻找第k小的数
{
	assert( (ar!=NULL) && (k>0) && (k<len+1) );

	int low = 0;
	int high = len - 1;

	int index = partition(ar, len, low, high);
	while(index != k-1)
	{
		if(index > k)
		{
			index = partition(ar, len, low, index-1);
		}
		else
		{
			index = partition(ar, len, index+1, high);
		}
	}
	return ar[index];
}

void findkmin(int *ar, int len, int k, int *retar)//寻找最小的k个数
{
	assert( (ar!=NULL) && (k>0) && (k<len+1) && (retar!=NULL));

	int low = 0;
	int high = len - 1;
	int index = partition(ar, len, low, high);
	
	while(index != k-1)
	{
		if(index > k)
		{
			index = partition(ar, len, low, index-1);
		}
		else
		{
			index = partition(ar, len, index+1, high);
		}
	}

	for(int i = 0; i<=index; ++i)
	{
		retar[i] = ar[i];
	}
}

void show(int *ar ,int len)
{
	for(int i=0; i<len; ++i)
	{
		cout<<ar[i]<<" ";
	}
	cout<<endl;
}

int main()
{
	int ar[] = {7,3,5,6,4,1,2};
	int retar[32];
	int len = sizeof(ar)/sizeof(ar[0]);
	int len2 = sizeof(retar)/sizeof(retar[0]);

	cout<<findkmin(ar, len, 7)<<endl;
	cout<<findkmin(ar, len, 1)<<endl;
	cout<<findkmin(ar, len, 5)<<endl;
	//cout<<findkmin(ar, len, 0)<<endl;
	//cout<<findkmin(ar, len, 8)<<endl;
	
	findkmin(ar, len, 7, retar);
	show(retar, 7);
	findkmin(ar, len, 1, retar);
	show(retar, 1);
	findkmin(ar, len, 5, retar);
	show(retar, 5);

	return 0;
}

O(n)时间复杂度求最小的k个数和第k小的数

标签:partition

原文地址:http://blog.csdn.net/huai1693838234/article/details/44907817

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!