Mon Dec 16 2019
STL Heap Sort
C++ Programming3716 views
File Name: stl-heap-sort.cpp
#include<iostream>
#include<algorithm>
using namespace std;
/* Preprocessor */
#define get_size(array) (sizeof((array))/sizeof((array[0])))
template<class t>
class sorting {
public:
sorting(t *list, int size) {
/* Create heap from data list */
make_heap(list,list+size);
/* Sort heap */
sort_heap(list,list+size);
}
};
int main() {
/* Sort integer */
int idata[] = {9,5,1,4,0,3,7,6,2,8};
sorting<int> isrt(idata, get_size(idata));
cout << "\nAfter sort:" << endl;
for(int i = 0; i < get_size(idata); i++)
cout << idata[i] << endl;
/* Sort float */
float fdata[] = {9.5,5.12,1.32,4.4,0.3,3.4,7.8,6.9,2.7,8.9};
sorting<float> fsrt(fdata, get_size(fdata));
cout << "\nAfter sort:" << endl;
for(int i = 0; i < get_size(fdata); i++)
cout << fdata[i] << endl;
/* Sort string */
string sdata[] = {"to","be","add","java","c++","python","sorting","new","search","c"};
sorting<string> ssrt(sdata, get_size(sdata));
cout << "\nAfter sort:" << endl;
for(int i = 0; i < get_size(sdata); i++)
cout << sdata[i] << endl;
}
/* Output */
After sort:
0
1
2
3
4
5
6
7
8
9
After sort:
0.3
1.32
2.7
3.4
4.4
5.12
6.9
7.8
8.9
9.5
After sort:
add
be
c
c++
java
new
python
search
sorting
to
Reference:
Author:Geekboots