This repository has been archived by the owner on Dec 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheapsort.c
executable file
·105 lines (82 loc) · 2.37 KB
/
heapsort.c
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <stdio.h>
#include <stdlib.h>
#include "heap.h"
#include "heap_max.h"
#include "heap_min.h"
#include "heapsort.h"
int *heapsort_ascending(int *array, int size) {
Heap heap = create_heap(size);
for (int i = 0; i < size; ++i)
heap_max_add(&heap, array[i]);
// printf("Heap max of size %d:\n", heap.size);
// for (int i = 0; i < heap.size; ++i)
// printf("%d ", heap.data[i]);
// printf("\n");
int *sorted_array = malloc(sizeof(int) * size);
for (int i = size - 1; i >= 0; --i) {
sorted_array[i] = heap_get_top(heap);
heap_max_pop(&heap);
}
// printf("Ascendingly sorted array:\n");
// for (int i = 0; i < size; ++i)
// printf("%d ", sorted_array[i]);
// printf("\n");
free(heap.data);
return sorted_array;
}
void inplace_heapsort_ascending(int *array, int size) {
Heap heap;
heap.capacity = size;
heap.size = 1;
heap.data = array;
while (heap.size < size)
heap_max_propagate_top(&heap, heap.size++);
// printf("Heap max of size %d:\n", heap.size);
// for (int i = 0; i < heap.size; ++i)
// printf("%d ", heap.data[i]);
// printf("\n");
for (int i = 0; i < size; ++i)
heap_max_pop(&heap);
// printf("Ascendingly sorted array:\n");
// for (int i = 0; i < size; ++i)
// printf("%d ", array[i]);
// printf("\n");
}
int *heapsort_descending(int *array, int size) {
Heap heap = create_heap(size);
for (int i = 0; i < size; ++i)
heap_min_add(&heap, array[i]);
// printf("Heap min of size %d:\n", heap.size);
// for (int i = 0; i < heap.size; ++i)
// printf("%d ", heap.data[i]);
// printf("\n");
int *sorted_array = malloc(sizeof(int) * size);
for (int i = size - 1; i >= 0; --i) {
sorted_array[i] = heap_get_top(heap);
heap_min_pop(&heap);
}
// printf("Descendingly sorted array:\n");
// for (int i = 0; i < size; ++i)
// printf("%d ", sorted_array[i]);
// printf("\n");
free(heap.data);
return sorted_array;
}
void inplace_heapsort_descending(int *array, int size) {
Heap heap;
heap.capacity = size;
heap.size = 1;
heap.data = array;
while (heap.size < size)
heap_min_propagate_top(&heap, heap.size++);
// printf("Heap min of size %d:\n", heap.size);
// for (int i = 0; i < heap.size; ++i)
// printf("%d ", heap.data[i]);
// printf("\n");
for (int i = 0; i < size; ++i)
heap_min_pop(&heap);
// printf("Descendingly sorted array:\n");
// for (int i = 0; i < size; ++i)
// printf("%d ", array[i]);
// printf("\n");
}