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

//思路:使用快速排序的patition函数来进行处理 时间复杂度为O(n)
#include
#include
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 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 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

你可能感兴趣的:(数据结构与算法)