-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathHeapSort.java
More file actions
69 lines (56 loc) · 1.61 KB
/
HeapSort.java
File metadata and controls
69 lines (56 loc) · 1.61 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
/*https://practice.geeksforgeeks.org/problems/heap-sort/1*/
class Solution
{
//returns the left child index
int left(int i) { return (2*i)+1; }
//returns the right child index
int right(int i) { return (2*i)+2; }
//building the heap
void buildHeap(int arr[], int n)
{
//for all non-leaf elements, call heapify in reverse direction
for (int i = (n/2)-1; i >= 0; --i)
heapify(arr,n,i);
}
//heapify
void heapify(int arr[], int n, int i)
{
//set maximum index to the root
int max = i;
//if left child is greater, update maximum index
if (left(i) < n && arr[left(i)] > arr[max])
max = left(i);
//if right child is greater, update maximum index
if (right(i) < n && arr[right(i)] > arr[max])
max = right(i);
//if root is not the maximum
if (max != i)
{
//swap root and maximum
int temp = arr[max];
arr[max] = arr[i];
arr[i] = temp;
//heapify the child
heapify(arr,n,max);
}
}
public void heapSort(int arr[], int n)
{
//build the heap
buildHeap(arr,n);
//set the new heap size
int index = n-1;
//till more than one elements exist
while (index > 0)
{
//swap the root with the last element of the heap
int temp = arr[0];
arr[0] = arr[index];
arr[index] = temp;
//heapify
heapify(arr,index,0);
//reduce the heap size
--index;
}
}
}