Shell Sort Program in Java

 In this programming tutorial of Java, we are implementing another sorting technique called Shell Sort. In Shell Sorting, the average time complexity of program is reduced to a greater extent.
In real terms, Shell sorting or Shell sort is just an extension of Insertion sort with some little modifications in the Shell sort algorithm. Shell sorting program in java is based on the algorithm that shell sort starts by comparing elements far apart, then elements less far apart, and finally by comparing adjacent elements.

Shell Sort Program Source code in Java

public class ShellSort {

   public static void main(String args[]) {

     int[] x =
     {547, 23, 523, 2378, 243, 7854, 14, 23, 310};

     System.out.println("Unsorted list: ");
     display(x);

     int inc[] = {5,3,1};
     int numinc = inc.length;

     shell(x, inc, numinc);
     System.out.println("Sorted list: ");
     display(x);
   }

   private static void shell
     (int x[], int inc[], int numinc) {

     int i, span, y, j, k;
     int n = x.length;

     for (i=0; i<numinc; i++) {

       span = inc[i];
       for(j=span; j<n; j++) {
         y = x[j];
         for (k=j-span; k>=0 && y<x[k]; k-=span)
           x[k+span] = x[k];

         x[k+span]=y;
       }
     }
   }


   private static void display(int x[]) {
     for (int i=0; i<x.length; i++)
       System.out.print(x[i] + " ");
     System.out.println("\n");
   }
}

Output of Shell Sort Java Program 

The above screenshot shows the accurate sorting output resulted from Shell Sort algorithm technique. Here in this program of Shell Sort in Java, we have taken 9 values in the array and have applied the Shell sort algorithm in Java programming language, which results in correct output. You can also make changes in this Shell sort algorithm program, by making it to take the values in shell sort program from users instead of predefined values. This Shell sort algorithm and program is very useful as it takes less time than other sorting techniques.

 

 

0 comments:

Post a Comment