Heap Sort
public class HeapDemo {
static int[] a;
static int n;
static int low;
static int high;
static int largest;
public static void main(String[] args) {
a = new int[]{54, 71, 36, 42, 16, 99, 10, 14, 88, 75};
System.out.println("Input array is :
");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + ",");
}
Heap(a);
for (int i = n; i > 0; i--) {
Swap(0, i);
n = n - 1;
maxheap(a, 0);
}
System.out.println("
");
System.out.println("Sorted array is :
");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + ",");
}
}
public static void Heap(int[] a) {
n = a.length - 1;
for (int i = n / 2; i >= 0; i--) {
maxheap(a, i);
}
}
public static void maxheap(int[] a, int i) {
low = 2 * i;
high = 2 * i + 1;
if (low <= n && a[low] > a[i]) {
largest = low;
} else {
largest = i;
}
if (high <= n && a[high] > a[largest]) {
largest = high;
}
if (largest != i) {
Swap(i, largest);
maxheap(a, largest);
}
}
public static void Swap(int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Output:
Input array is :
54,71,36,42,16,99,10,14,88,75,
Sorted array is :
10,14,16,36,42,54,71,75,88,99,