面试题30—最小的k个数

题目:输入n个整数,找出其中的最小k个数。

代码示例:

#include<iostream>
#include<time.h>
using namespace std;
void SwapTwoNum(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}

int Partion(int a[], int length, int start, int end)
{
	if (a == NULL || length <= 0 || start > end)
		throw "error";
	
	
	srand((unsigned int)time(NULL));
	int index = rand() % (end - start + 1) + start;
	SwapTwoNum(a[index], a[end]);
	int small = start - 1;
	for (int index = start; index < end; index++)
	{
		if (a[index] < a[end])
		{
			small++;
			if (small != index)
			{
				SwapTwoNum(a[small], a[index]);
			}
		}
	}
	small++;
	SwapTwoNum(a[small], a[end]);

	return small;
}
void FindKSmall(int a[], int length,int start,int end,int k)
{
	if (a == NULL || length <= 0||k>length||start>end)
		return;


	int index = Partion(a, length, start, end);
	
	while (index != k - 1)
	{
		if (index > k - 1)
		{
			index = Partion(a, length, start, index - 1);
		}
		else
		{
			index = Partion(a, length, index + 1, end);
		}
	}
}


int main()
{
	const int n = 10;
	int k = 5;
	int a[n] = { 7, 3, 2, 6, 9, 0, 12, 10, 32, 5 };
	cout << "原数组:";
	for (int i = 0; i < n; i++)
		cout << a[i] << " ";
	cout << endl;

	cout << "最小的" << k << "个数:";
	FindKSmall(a, n, 0, n - 1, k);
	for (int i = 0; i < k; i++)
		cout << a[i] << " ";
	cout << endl;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值