-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.h
More file actions
71 lines (64 loc) · 2.09 KB
/
Copy pathheap.h
File metadata and controls
71 lines (64 loc) · 2.09 KB
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
/***********************************************************************
* Program:
* Week 11, Sorting
* Brother Ercanbrack, CS 235
*
* Author:
* Ryan Walker
* Summary:
* This is the implementation of a heap sort. It will receive a vector
* and sort its contents similar to a binary search tree. While percolating
* down is a method for doing a heap sort, I found it much easier to have
* it percolate recursively.
************************************************************************/
#include <vector>
using namespace std;
/*************************************************************************
* heapify
* This function is recursive and will sort a vector(or potentially an array).
* It places the largest value at the end of the vector and continues to swap
* values placing the next largest value at the front of the sorted section
* of the array.
**************************************************************************/
template<class T>
void heapify(vector<T> & data, int num, int i)
{
int largest = i;
int leftChild = 2 * i + 1;
int rightChild = 2 * i + 2;
// is the left child greater?
if (leftChild < num && data[leftChild] > data[largest])
largest = leftChild;
// or is the right child greater?
if (rightChild < num && data[rightChild] > data[largest])
largest = rightChild;
if (largest != i)
{
// swap places, putting the next largest value at the
// front of the sorted section of the array
swap(data[i], data[largest]);
// go again
heapify(data, num, largest);
}
}
/*************************************************************************
* heapSort
* This function sorts a vector using a heap sort.
* Input: data - Vector to be sorted.
* Output: data - Vector sorted
**************************************************************************/
template<class T>
void heapSort(vector<T> &data)
{
for (int i = data.size() / 2 - 1; i >= 0; i--)
{
// heapifys the data
heapify(data, data.size(), i);
}
for (int i = data.size() - 1; i >= 0; i--)
{
// starts at the end of the heap and works its way up
swap(data[0], data[i]);
heapify(data, i, 0);
}
}