forked from souvikg544/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
67 lines (58 loc) · 2.06 KB
/
HeapSort.java
File metadata and controls
67 lines (58 loc) · 2.06 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
class HeapSort{
void print(int array[],int size){
int index = 0;
while(index < size){
System.out.print(" " + array[index]);
index++;
}
}
void heapify(int arr[], int size, int index){
int maximum = index;
int leftChild = 2*index + 1;
int rightChild = 2*index + 2;
int swapper;
//now check if right and left child are greater than parent and the right and left child index are not out of bound.
if(leftChild < size && arr[leftChild] > arr[maximum]){
maximum = leftChild;
}
if(rightChild < size && arr[rightChild] > arr[maximum]){
maximum = rightChild;
}
//if maximum is not equal to its initial declaration(root) then swap.
if(maximum != index){
swapper = arr[index];
arr[index] = arr[maximum];
arr[maximum] = swapper;
//we will recursively heapify the affected sub-tree
heapify(arr,size,maximum);
}
}
void sort(int array[]){
int size = array.length;
int swapper;
//building max heap using heapify
int index = (size/2) - 1;
while(index >=0){
heapify(array,size,index);
index--;
}
//We will extract elements from heap one by one and reduce size of the heap (assuming part of array is sorted controlled by index)
for(index = size -1; index > 0; index--){
//largest resides on root in max-heap
swapper = array[0];
array[0] = array[index];
array[index] = swapper;
//call heapify on root of reduced heap
heapify(array,index, 0);
}
}
public static void main(String args[])
{
int array[] = { 3, 1, 4, 9, 8, 6 };
int size = array.length;
HeapSort object = new HeapSort();
object.sort(array);
System.out.println("After Heap Sort: ");
object.print(array,size);
}
}