public class HeapSort {
public void heapSort(int a[], int n) {
if(a==null)
return;
if(n<1)
return;
for (int i = n-1; i >= 1; i--) {
swap(a,0,i);
heapAdjust(a, 0, i);
}
}
public void heapAdjust(int a[], int i, int n) {
int temp = a[i];
int j = 2 * i + 1;
while (j < n) {
if (j+1<n && a[j + 1] < a[j])
j++;
if (a[j] >= temp)
break;
a[i] = a[j];
i = j;
j = 2 * j + 1;
}
a[i] = temp;
}
public static void main(String args[]) {
int a[] = { 1, 2, 5, 4, 3 };
new HeapSort().heapSort(a,a.length);
for(int i:a){
System.out.print(i);
}
}
public void swap(int a[],int i,int j){
int temp =a[i];
a[i]=a[j];
a[j]=temp;
}
}
public void heapSort(int a[], int n) {
if(a==null)
return;
if(n<1)
return;
for (int i = n-1; i >= 1; i--) {
swap(a,0,i);
heapAdjust(a, 0, i);
}
}
public void heapAdjust(int a[], int i, int n) {
int temp = a[i];
int j = 2 * i + 1;
while (j < n) {
if (j+1<n && a[j + 1] < a[j])
j++;
if (a[j] >= temp)
break;
a[i] = a[j];
i = j;
j = 2 * j + 1;
}
a[i] = temp;
}
public static void main(String args[]) {
int a[] = { 1, 2, 5, 4, 3 };
new HeapSort().heapSort(a,a.length);
for(int i:a){
System.out.print(i);
}
}
public void swap(int a[],int i,int j){
int temp =a[i];
a[i]=a[j];
a[j]=temp;
}
}