#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;
}
找出数组从小到大的前N个数
最新推荐文章于 2022-01-15 10:30:06 发布