skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Monday, August 11, 2014

To Sort an Interger Array using Shell Sort

Posted by Happy Coder at 4:37 PM – 0 comments
 
To Sort an Interger Array using Shell Sort

class ShellSort {

    public static int[] shellSort(int[] array) {
  int N = array.length;
  
  // determine the initial h value
  int h = 1;
     while (h < N / 3) 
      h = 3 * h + 1; // 1, 4, 13, 40, 121, 364, 1093, ...
     
     while (h >= 1) {
      // h-sort the array
      for (int i = h; i < array.length; i++) {
       // do insertion sort for h-sized array
       for (int j = i; j >= h && array[j] < array[j - h]; j -= h)
        swap(array, j, j - h);
      }
      
      h = h / 3; // reverse the h-size
     }
     
     return array;
 }
 
 /*
  * swaps data elements between 2 indexes of an array
  */
 private static void swap(int[] array, int i, int j) {
  int temp = array[i];
  array[i] = array[j];
  array[j] = temp;
 } 
    
    public static void  main(String args[]){
     ShellSort sSort = new ShellSort();
     int[] array = { 77, 99, 44, 55, 22, 88, 11, 0, 66, 33 };
     int[] sortedArray = sSort.shellSort(array);
     for (int i = 0; i < array.length; i++)
         System.out.println(sortedArray[i]);
     
    }
}

Output of the Program : 
0
11
22
33
44
55
66
77
88
99

Try it by yourself here : http://ideone.com/veRv5P
Labels: Algorithm , Sorting Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger