找出数组从小到大的前N个数

#include <iostream>
using namespace std;

void print_array(int* array, int size)
{
	for (int i=0; i<size; i++)
		cout << array[i] << " ";
	cout << endl;
}

void selection_sort(int* array, int size)
{
	for (int i=0; i<size; i++)
		for (int j=i; j<size; j++)
		{
			if (array[j] < array[i])
			{
				int temp = array[j];
				array[j] = array[i];
				array[i] = temp;
			}
		}
}

void heapify(int* array, int size, int node)
{
	if (node > size / 2)
		return ;

	int left_child = node * 2 + 1;
	int right_child = node * 2 + 2;
	int max_node = node;

	if (left_child < size && array[left_child] > array[max_node])
	{
		max_node = left_child;
	}

	if (right_child < size && array[right_child] > array[max_node])
	{
		max_node = right_child;
	}

	if (max_node != node)
	{
		swap(array[node], array[max_node]);
		heapify(array, size, max_node);
	}
}

void build_heap(int* array, int size)
{
	int i = size / 2;
	for (; i>=0; i--)
	{
		heapify(array, size, i);
	}
}

// n is less than size of array
void find_first_n_elems(int* array, int size, int n)
{
	build_heap(array, n); 
	cout << "after building the heap for the first " << n << " elements:" << endl;
	print_array(array, n);

	for (int i=n; i<size; i++)
	{
		cout << "Compare element " << array[i] << ":";
		if (array[i] < array[0])
		{
			swap(array[i], array[0]);
			heapify(array, n, 0);
			print_array(array, n);
		}
		else
		{
			cout << " Ignored." << endl;
		}
	}

	cout << "The first n elements is:";
	for (int i=0; i<n; i++)
	{
		cout << array[i] << " ";
	}
	cout << endl;
}

void main()
{
	int* array;
	int size;
	cout << "Input the size:" << endl;
	cin >> size;

	array = new int[size];
	for (int i=0; i<size; i++)
		array[i] = rand()%100;
	
	print_array(array, size);

	int n;
	cout << "Input the n you want:" << endl;
	cin >> n;

	find_first_n_elems(array, size, n);

	cout << "[prompt]" << endl;
	selection_sort(array, size);
	print_array(array, size);

	delete[] array;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值