Friday, July 20, 2012

Heap Sort Using Java

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 import java.util.Scanner;  
 class heap{  
     private static int[] a;  
   private static int n;  
   
     public static void sort(int[] array){  
     //Initialize parsed array to variables        
     a=array;  
       n=a.length;  
       heapsort();  
     }  
     //Start counting time.  
   long start = System.nanoTime();  
     private static void heapsort(){  
       buildheap(); //build a heap using entered values.  
     //elements after building heap  
     System.out.println("\n"+"Entered Values as Heap :");  
     for(int i=0;i<a.length;i++){  
       System.out.print(a[i]+",");  
     }  
     System.out.println("");  
       while (n>1){  
           n--;  
           exchange (0, n);  
           downheap (0);  
       }  
     System.out.println("\n"+"Entered values after Heap Sort :");  
     for(int j=0;j<a.length;j++){  
       System.out.print(+a[j]+",");  
     }  
     System.out.println("\n");  
     }  
 //Building a heap using input values  
     private static void buildheap(){  
       for (int v=n/2-1; v>=0; v--)  
           downheap (v);  
     }  
 //Heap property checker  
     private static void downheap(int v){  
       int w=2*v+1;  // first descendant of v  
         while (w<n){  
           if (w+1<n)  // is there a second descendant?  
             if (a[w+1]>a[w])  
           w++;  // w is the descendant of v with maximum label  
   
           if (a[v]>=a[w])  
         return; // v has heap property  
           // otherwise  
           exchange(v, w); // exchange labels of v and w  
           v=w;    // continue  
           w=2*v+1;  
       }  
     }  
 //elements swapping method to heap property  
     private static void exchange(int i, int j){  
       int t=a[i];  
       a[i]=a[j];  
       a[j]=t;  
     }  
   long end = System.nanoTime();  
   //end counting time.  
 }  // end class heap  
   
 //new class for user input  
 public class heapsort{  
   public static void heapsort(){  
     System.out.println("");  
     Scanner scan=new Scanner(System.in);  
     try{  
       System.out.print("Enter number of values you want to sort :");  
       int length=scan.nextInt();  
       int[] arr=new int[length];  
       //System.out.println("Enter integer values you want to sort :");  
       for(int i=0;i<arr.length;i++){  
         System.out.print("Enter "+ (i+1)+ " number: ");  
         arr[i]=scan.nextInt();  
       }  
       heap hs=new heap();  
       hs.sort(arr);  
       long elapsedTime = hs.end - hs.start;  
       System.out.println("Running time of heap sort ="+elapsedTime + " nano seconds");  
     }catch(Exception e){  
       System.out.println("Error in input");  
     }  
   }  
 }  

0 comments:

Post a Comment