1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
void heapsort(int data[], size_t n);
void make_heap(int data[], size_t size);
void reheapify_down(int data[], size_t n);
void heapsort(int data[], size_t n);
int main()
{
int arry[] = {21, 35, 22, 27, 23, 45, 42, 19, 4, 5};
cout <<"Original Data: ";
for(int i = 0; i < 10; i++)
{
cout << arry[i] << " ";
}
cout << endl;
heapsort(arry, 10);
//make_heap(arry, 10);
cout <<"\nNew Data: ";
for(int i = 0; i < 10; i++)
{
cout <<arry[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
void make_heap(int data[], size_t size)
{
size_t i;
size_t k;
size_t temp;
for(i = 1; i < size; ++i)
{
k = i;
while((data[k] != data[0]) && (data[k] > data[(k -1) / 2]))
{
temp = data[k];
data[k] = data[(k-1)/2];
data[(k-1)/2] = temp;
k = (k-1)/2;
}
}
}
void reheapify_down(int data[], size_t n)
{
size_t current;
size_t big_child_index;
bool heap_ok;
current = 0;
heap_ok = false;
while((!heap_ok) && ((2 * current) + 1 < n) && ((2 * current) + 2 < n))
{
if(data[(2*current) + 1] > data[current] && ((2*current) + 1 < n))
{
big_child_index = (2 * current) + 1;
}
if(data[(2*current)+2] > data[current] && ((2*current)+2 < n))
{
big_child_index = (2 * current) + 2;
}
if(data[current] < data[big_child_index])
{
int temp = data[current];
data[current] = data[big_child_index];
data[big_child_index] = temp;
current = big_child_index;
}
else
heap_ok = true;
}
}
void heapsort(int data[], size_t n)
{
size_t unsorted;
make_heap(data, n);
cout << "Heap Data: ";
for (int i = 0; i < n; ++i)
{
cout << data[i] << " ";
}
unsorted = n;
while(unsorted > 1)
{
--unsorted;
swap(data[0], data[unsorted]);
reheapify_down(data, unsorted);
}
}
|