-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_sort.c
More file actions
83 lines (71 loc) · 1.36 KB
/
heap_sort.c
File metadata and controls
83 lines (71 loc) · 1.36 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
72
73
74
75
76
77
78
79
80
81
82
83
#include<stdio.h>
#include<stdlib.h>
void heapify_down();
void heapify_up();
void print_arr(int*, int);
//Global heap array
int* heap;
int _index;
void swap(int i, int j) {
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
void heap_push(int a) {
heap[_index++] = a;
heapify_up();
}
int heap_pop() {
int temp = heap[0];
heapify_down();
return temp;
}
void heapify_up() {
int i = _index - 1;
while(i > 0 && heap[i] < heap[(i-1)/2]) {
swap(i, (i-1)/2);
i = (i-1)/2;
}
}
void heapify_down() {
heap[0] = heap[--_index];
for (int i=0; i<(_index - 1)/2; i++) {
if (heap[2*i+1] < heap[2*i+2]) {
if (heap[i] > heap[2*i+1]) {
swap(i, 2*i+1);
i = 2*i+1;
}
}
else {
if (heap[i] > heap[2*i+2]) {
swap(i, 2*i+2);
i = 2*i+2;
}
}
}
}
void heap_sort(int* arr, int size) {
for (int i=0; i<size; i++)
heap_push(arr[i]);
for (int i=0; i<size; i++)
arr[i] = heap_pop();
}
void initialize_heap(int size) {
heap = (int*)malloc(size*sizeof(int));
for(int i=0; i<size; i++)
heap[i] = 99;
_index = 0;
}
void print_arr(int* arr, int size) {
for(int i=0; i<size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[10] = {9, 4, 5, 7, 10, 1, 0, 3};
int size = sizeof(arr)/sizeof(arr[0]);
initialize_heap(size);
heap_sort(arr, size);
print_arr(arr, size);
return 0;
}