-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapSort.cpp
More file actions
54 lines (47 loc) · 922 Bytes
/
heapSort.cpp
File metadata and controls
54 lines (47 loc) · 922 Bytes
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
#if 0
#include <iostream>
#include <algorithm>
using namespace std;
void heapify(int* A, int k, int n);
void buildHeap(int* A, int n) {
for (int i = (n-1) / 2;i >= 0; i--) {
heapify(A, i, n-1);
}
}
void heapify(int* A, int k, int n) {
int left = 2*k;
int right = 2*k + 1;
int smaller = 0;
if (right <= n) {
if (A[left] < A[right])
smaller = left;
else
smaller = right;
}
else if (left <= n)
smaller = left;
else
return;
if (A[smaller] < A[k]) {
swap(A[k], A[smaller]);
heapify(A, smaller, n);
}
}
void heapSort(int* A, int n) {
buildHeap(A, n);
for (int i = n - 1; i > 0; i--) {
swap(A[0], A[i]);
heapify(A, 0, i - 1);
}
}
int main(void) {
int Array[] = { 12,3,6,23,56,73,3,63,2,35,54 };
int length = sizeof(Array) / sizeof(Array[0]);
heapSort(Array, length);
//buildHeap(Array, length);
for (int i = 0; i < length; i++) {
cout << Array[i] << " ";
}
return 0;
}
#endif