Advertisement
chowdhury_riham

Heap Sort

Oct 14th, 2017
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. import java.util.Scanner;
  2. public class HeapSort {
  3.     public static int[] vertex;
  4.     public static int n;
  5.     public static void main(String[] args){
  6.         Scanner sc=new Scanner(System.in);
  7.         System.out.println("please enter vertex number");
  8.         n=sc.nextInt();
  9.         vertex=new int[n+1];
  10.         System.out.println();
  11.         System.out.println("please enter the inputs");
  12.         for(int j=1;j<=n;j++){
  13.             vertex[j]=sc.nextInt();
  14.         }
  15.        heapSort(vertex);
  16.        printHeap();
  17.     }
  18.    public static void heapify(int i,int n){
  19.        int l=left(i);
  20.        int r=right(i);
  21.        int largest=i;
  22.        if (l<=n && vertex[l]>vertex[i]){
  23.            largest=l;
  24.        }
  25.        if(r<=n && vertex[r]>vertex[largest]){
  26.            largest=r;
  27.        }
  28.        if(i!=largest){
  29.            swap(i,largest);
  30.            heapify(largest,n);    
  31.        }
  32.     }
  33.    public static int left(int i){
  34.        return 2*i;
  35.    }
  36.     public static int right(int i){
  37.         return 2*i+1;
  38.     }
  39.     public static void buildHeap(){
  40.         for(int i=n/2;i>0;i--){
  41.             heapify(i,n);
  42.         }
  43.     }
  44.     public static void heapSort(int[] v){
  45.         buildHeap();
  46.         for(int i=n;i>1;i--){
  47.             swap(1,i);
  48.             n--;
  49.             heapify(1,i-1);
  50.         }
  51.     }
  52.     public static void swap(int i,int j){
  53.         int temp= vertex[i];
  54.         vertex[i]=vertex[j];
  55.         vertex[j]=temp;
  56.     }
  57.     public static void printHeap(){
  58.         System.out.println("The sorted List");
  59.         for(int p=1;p<vertex.length;p++){
  60.             System.out.print(vertex[p]+"\t");
  61.         }
  62.    
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement