forked from TheAlgorithms/C
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.c
More file actions
70 lines (65 loc) · 1.45 KB
/
Copy pathHeapSort.c
File metadata and controls
70 lines (65 loc) · 1.45 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
// Heap sort
#include <stdio.h>
void printArr(int *A, int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", A[i]);
}
printf("\n");
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// heap looks like
// 9 1 2 8 3 4 7 5
// 9 8 4 7
// 9 7
// 9
// the array is heap mean arr[i]>max(arr[i*2+1],arr[i*2+2])
// the arr[0] is max of the array
void heapShift(int *arr, int index, int size)
{
// put arr[index] to arr[index+1..size-1] follow heap
int i = index;
int j = 2 * i + 1;
while (j < size)
{
if (j != size - 1) // there exist j and j+1
{
if (arr[j + 1] > arr[j]) // find max of arr[j] and arr[j+1]
j++;
}
if (arr[i] > arr[j]) // already heap
break;
swap(&arr[i], &arr[j]);
// move i, j
i = j;
j = i * 2 + 1;
}
}
void heapSort(int *arr, int size)
{
// the array is split to to half
// just care the first half to put heap
for (int i = size / 2; i >= 0; i--)
{
heapShift(arr, i, size);
}
for (int i = size - 1; i >= 0; i--)
{
swap(&arr[0], &arr[i]); // move max of array to the end
heapShift(arr, 0, i); // find max of arr[0..i-1], move to arr[0]
}
}
int main()
{
int A[] = {9, 8, 7, 6, 5, 4, 3, 2, 1};
int size = sizeof(A) / sizeof(A[0]);
heapSort(A, size);
printArr(A, size);
return 0;
}