-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathHeapSort in Java
50 lines (42 loc) · 1.04 KB
/
HeapSort in 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
class Solution
{
//Heapify function to maintain heap property.
void heapify(int a[], int n, int i)
{
// Your code here
int largest = i;
int l = (2*i) + 1;
int r = (2*i) + 2;
if(l<n && a[l]>a[largest])
largest = l;
if(r<n && a[r]>a[largest])
largest = r;
if(largest!=i){
swap (a, i , largest);
heapify(a, n, largest);
}
}
//Function to build a Heap from array.
public void buildHeap(int a[], int n)
{
// Your code here
for(int i = (n-1)/2 ; i>=0; i--){
heapify(a,n,i);
}
}
//Function to sort an array using Heap Sort.
public void heapSort(int a[], int n)
{
//code here
buildHeap(a,n);
for(int i=n-1;i>0;i--){
swap(a, 0 , i);
heapify(a,i,0);
}
}
public static void swap(int[]a,int i, int j){
int temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}