-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeapSort.java
50 lines (46 loc) · 1.31 KB
/
HeapSort.java
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
import java.util.*;
//time complexity = O(nlogn)
public class HeapSort {
public static void heapify(int arr[],int i, int size){
int left = 2*i+1;
int right=2*i+2;
int maxIndex=i;
if(left<size&& arr[left]>arr[maxIndex]){
maxIndex = left;
}
if(right<size&& arr[right]>arr[maxIndex]){
maxIndex = right;
}
if(maxIndex!=i){
//swap
int temp = arr[i];
arr[i]=arr[maxIndex];
arr[maxIndex]=temp;
heapify(arr,maxIndex,size);
}
}
public static void heapSort(int arr[]){
//1. convert arr into maxHeap
//for all leaf nodes we call heapify
int n=arr.length;
for(int i=n/2;i>=0;i--){
heapify(arr, i,n); //time complexity = logn*n
}
//2. Push largest element to the end
//ie we swap the element at index 0 with our last element
for(int i=n-1; i>0; i--){
//swap
int temp = arr[0];
arr[0]=arr[i];
arr[i]=temp;
heapify(arr,0,i);
}
}
public static void main(String[] args) {
int arr[]={1,2,4,5,3};
heapSort(arr);
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]+" ");
}
}
}