// HeapSort
/********************************************
aim: to sort an array in ascending order.
1. making a max-heap firstly(biggest on top). using siftup function (siftdown works as well if you like).
2. sorting the heap by swapping the fisrt node(top) and the last node(leaf), so the last node is sorted.
3. makeing a max-heap again for the rest of nodes(except for the sorted nodes(numbers)).
4. repeat step 2 and 3 for the unsorted nodes, until the number of sorted node is one.
Note: I'm going to use siftup function, and the siftdown function will be presented as well,
these two functions do the same thing, you can choose anyone you like.
*********************************************/
#include <iostream>
using namespace std;
void SwapTwo(int &a, int &b)
{
int temp = a;
a = b;
b= temp;
}
void siftup(int nums[], int i) // comparation between the current node and its parent, swap two if necessary
{
if(i==0) return;
int p = (i-1)/2;
if (nums[i]<nums[p]) return;
else // if the node is larger than its parent, swap them and do siftup again to make sure
{ // the node is less than it's new parent
SwapTwo(nums[i], nums[p]);
siftup(nums, p);
}
}
/*
void siftdown(int nums[], int i, int size)
{
int c = 2*i+1;
if (c >= size)
{
return;
}
if ((c+1<size) && (nums[c+1] > nums[c]))
{
c++;
}
if (nums[c] > nums[i])
{
SwapTwo(nums[c], nums[i]);
siftdown(nums, c, size);
}
}
*/
// to make a max-heap(largest on top)
void MakeHeap(int nums[], int size)
{
for (int i=0; i<size; i++) // using siftup function
siftup(nums, i);
//for (int i=size-1; i>=0; i--) // or you can use siftdown function
// siftdown(nums, i, size);
}
// to print an array
void Display(int nums[], int size)
{
for (int i=0; i<size; i++)
{
cout << nums[i]<<endl;
}
}
// to sort an array
void HeapSort(int nums[], int size)
{
for (int i=size-1; i>=0; i--)
{
SwapTwo(nums[i], nums[0]); // step 2, swapping the fisrt node(top) and the last node(leaf).
size--; // remove the sorted numbers.
MakeHeap(nums, size); // make max-heap for unsorted numbers.
}
}
int main()
{
int nums[10] = {34,4,56,67,78,5,345,234,435,456};
int size = sizeof(nums)/sizeof(int);
MakeHeap(nums, size);
HeapSort(nums, size);
Display(nums, size);
return 0;
}
C++ 堆排序 (HeapSort)
最新推荐文章于 2021-10-09 10:48:02 发布