import java.util.Scanner;
public class HeapSort {
public static void main(String args[]) {
int n;
int num[];
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the number of elements
:");
n = Integer.parseInt(scan.nextLine());
System.out.println("Enter the numbers :");
num = new int[n];
for(int i=0; i<n; i++) {
num[i] = Integer.parseInt(scan.nextLine());
}
for(int i=n; i>1; i--) {
HeapSort(num, i - 1);
}
System.out.println("\nHeap sorted list are");
for(int i=0; i<n; i++) {
System.out.print(" " + num[i]);
}
}
private static void HeapSort(int array[], int bound) {
int left, right, middle, root, temp;
root = (bound-1) / 2;
for(int i=root; i>=0; i--) {
for(int j=root; j>=0; j--) {
left = (2*j) + 1;
right = (2*j) + 2;
if((left <= bound) && (right <= bound)) {
if(array[right] >= array[left])
middle = right;
else
middle = left;
}
else {
if(right > bound)
middle = left;
else
middle = right;
}
if(array[j] < array[middle]) {
temp = array[j];
array[j] = array[middle];
array[middle] = temp;
}
}
}
temp = array[0];
array[0] = array[bound];
array[bound] = temp;
}
}
OUTPUT:-
C:\Users\saty\Desktop>javac HeapSort.java
C:\Users\saty\Desktop>java HeapSort
Enter the number of elements :
8
Enter the numbers :
45
8
72
34
5
1
9
34
Heap sorted list are
1 5 8 9 34 34 45 72
This guy is really a good teacher.
ReplyDeleteAwesome tutorial thank u....:)
ReplyDelete