Skip to content

Commit d9877a3

Browse files
committed
Merge pull request xtaci#8 from xmuliang/master
add heap sort
2 parents e8fc083 + 3a442bb commit d9877a3

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed

include/heap_sort.h

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*******************************************************************************
2+
* DANIEL'S ALGORITHM IMPLEMENTAIONS
3+
*
4+
* /\ | _ _ ._ o _|_ |_ ._ _ _
5+
* /--\ | (_| (_) | | |_ | | | | | _>
6+
* _|
7+
*
8+
* HEAPSORT
9+
*
10+
* Features:
11+
* 1. Although somewhat slower in practice on most machines than a well-implemented quicksort,
12+
it has the advantage of a more favorable worst-case O(n log n) runtime
13+
*
14+
* http://en.wikipedia.org/wiki/Heapsort
15+
*
16+
******************************************************************************/
17+
18+
#ifndef __HEAPSORT_H__
19+
#define __HEAPSORT_H__
20+
21+
#include <heap.h>
22+
23+
namespace alg
24+
{
25+
26+
27+
/**
28+
* heap sort an array
29+
*/
30+
template<typename T>
31+
static void heapsort(T *array,int number_of_elements)
32+
{
33+
Heap<T> heap(number_of_elements);
34+
int i;
35+
36+
/*In order to build a heap structure from input array*/
37+
for(i=0;i<number_of_elements;i++)
38+
{
39+
heap.insert(array[i],0); //set key with the value of the array,value to 0(no use)
40+
}
41+
42+
/*Temporary array to store the minkey of each step,which is deleted from the heap*/
43+
T tempArray[number_of_elements];
44+
for(i=0;i<number_of_elements;i++)
45+
{
46+
tempArray[i]=heap.min_key(); //find the min key
47+
heap.delete_min();
48+
}
49+
50+
for(i=0;i<number_of_elements;i++)
51+
{
52+
array[i]=tempArray[i]; //copy back to the original array
53+
}
54+
}
55+
}
56+
57+
#endif //
58+

src/heap_sort_demo.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <time.h>
4+
5+
#include "generic.h"
6+
#include "heap_sort.h"
7+
8+
using namespace alg;
9+
10+
int main()
11+
{
12+
const int MAX_ELEMENTS = 10;
13+
int list[MAX_ELEMENTS];
14+
15+
int i = 0;
16+
17+
srand(time(NULL));
18+
// generate random numbers and fill them to the list
19+
for(i = 0; i < MAX_ELEMENTS; i++ ){
20+
list[i] = rand()%100;
21+
}
22+
printf("The list before sorting is:\n");
23+
printlist(list,MAX_ELEMENTS);
24+
25+
// sort the list using heap sort
26+
heapsort<int>(&list[0],MAX_ELEMENTS);
27+
28+
// print the result
29+
printf("The list after sorting using heapsort algorithm:\n");
30+
printlist(list,MAX_ELEMENTS);
31+
return 0;
32+
}
33+
34+

0 commit comments

Comments
 (0)