forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
heapSort.java
39 lines (38 loc) · 1.18 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
import java.util.Scanner;
public class heapSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++) arr[i] = sc.nextInt();
creatHeap(arr,n); //buiulding max heap
for(int i=n-1;i>0;i--){
//swapping with last element
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
heapify(arr,i,0);
}
for(int i:arr) System.out.print(i + ",");
System.out.println();
}
//createHeap
public static void creatHeap(int[] arr,int n){
for(int i=n/2;i>=0;i--){
heapify(arr,n,i);
}
}
public static void heapify(int[] arr,int n,int i){
int maxIdx = i;
int leftIdx = 2*i + 1;
int rightIdx = 2*i + 2;
if(leftIdx < n && arr[maxIdx] < arr[leftIdx]) maxIdx = leftIdx;
if(rightIdx < n && arr[maxIdx] < arr[rightIdx]) maxIdx = rightIdx;
if(maxIdx != i){
int temp = arr[maxIdx];
arr[maxIdx] = arr[i];
arr[i] = temp;
heapify(arr,n,maxIdx);
}
}
}