Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class HeapSort {
- public static int[] vertex;
- public static int n;
- public static void main(String[] args){
- Scanner sc=new Scanner(System.in);
- System.out.println("please enter vertex number");
- n=sc.nextInt();
- vertex=new int[n+1];
- System.out.println();
- System.out.println("please enter the inputs");
- for(int j=1;j<=n;j++){
- vertex[j]=sc.nextInt();
- }
- heapSort(vertex);
- printHeap();
- }
- public static void heapify(int i,int n){
- int l=left(i);
- int r=right(i);
- int largest=i;
- if (l<=n && vertex[l]>vertex[i]){
- largest=l;
- }
- if(r<=n && vertex[r]>vertex[largest]){
- largest=r;
- }
- if(i!=largest){
- swap(i,largest);
- heapify(largest,n);
- }
- }
- public static int left(int i){
- return 2*i;
- }
- public static int right(int i){
- return 2*i+1;
- }
- public static void buildHeap(){
- for(int i=n/2;i>0;i--){
- heapify(i,n);
- }
- }
- public static void heapSort(int[] v){
- buildHeap();
- for(int i=n;i>1;i--){
- swap(1,i);
- n--;
- heapify(1,i-1);
- }
- }
- public static void swap(int i,int j){
- int temp= vertex[i];
- vertex[i]=vertex[j];
- vertex[j]=temp;
- }
- public static void printHeap(){
- System.out.println("The sorted List");
- for(int p=1;p<vertex.length;p++){
- System.out.print(vertex[p]+"\t");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement