Friday, July 20, 2012

Shell 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.*;  
   
 class shell{  
   //Start counting time.  
   long start = System.nanoTime();  
   public static void shell(int[] a) {  
     int increment = a.length / 2;  //select partitions.  
     //System.out.println("\n"+"increment is "+increment+"\n");  
     while (increment > 0) {  
       System.out.println("increment is "+increment);  
       for (int i = increment; i < a.length; i++) { //select elements and sort.  
         int j = i;  
         int temp = a[i];  
         while (j >= increment && a[j - increment] > temp) { //sort selected elements.  
           a[j] = a[j - increment];  
           j = j - increment;  
   
         }  
         a[j] = temp;  
       }  
       increment=increment/2; //partition the array again  
     }  
   }  
   long end = System.nanoTime();  
   //end counting time.  
 }  
 public class shellsort{  
   public static void shellsort(){  
     System.out.println("");  
     Scanner scan=new Scanner(System.in);  
     try{  
       System.out.print("Enter number of elements 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();  
       }  
       shell sh=new shell();  
       sh.shell(arr);  
       System.out.println("\n"+ "Sorted values :");  
       for(int j=0;j<arr.length;j++){  
         System.out.print(arr[j]+",");  
       }  
       System.out.println("");  
       long elapsedTime = sh.end - sh.start;  
       System.out.println("\n"+"Running time of heap sort ="+elapsedTime + " nano seconds"+"\n");  
     }catch(Exception e){  
       System.out.println("Error in input");  
     }  
   }  
   
 }  

0 comments:

Post a Comment