Java Program for ShellSort

Java 8Server Side ProgrammingProgramming

Shell sort is a sorting technique that is similar to insertion sort, wherein elements are sorted which are at far ends (either ends) of the array. This way, the interval size between the next and the second to last element reduces. This happens for all the elements in the array until the interval distance is reduced to 0.

Example

Following is an example for ShellSort in Java −

 Live Demo

public class Demo {
   int shell_sort(int my_arr[]) {
      int arr_len = my_arr.length;
      for (int gap = arr_len / 2; gap > 0; gap /= 2) {
         for (int i = gap; i < arr_len; i += 1) {
            int temp = my_arr[i];
            int j;
            for (j = i; j >= gap && my_arr[j - gap] > temp; j -= gap)
            my_arr[j] = my_arr[j - gap];
            my_arr[j] = temp;
         }
      }
      return 0;
   }
   public static void main(String args[]) {
      int my_arr[] = { 12, 34, 54, 2, 3 };
      Demo my_instance = new Demo();
      my_instance.shell_sort(my_arr);
      System.out.println("The array, after performing shell sort is : ");
      int arr_len = my_arr.length;
      for (int i = 0; i < arr_len; ++i)
      System.out.print(my_arr[i] + " ");
      System.out.println();
   }
}

Output

The array, after performing shell sort is :
2 3 12 34 54

Explanation

This algorithm sorts the elements that are far apart from each other, thereby reducing the interval between those two elements. It can be understood as being a generalized version of insertion sort. Elements at specific intervals in an array are sorted first, their interval distance reduces, thereby sorting all elements in the process.

When the first loop is iterated, the size of the array is taken and elements between size/2 are compared and swapped if they are not sorted. The same thing is repeated for all other elements. The elements are sorted by defining a temporary variable, and swapping the elements.

In the second loop iteration, size/4 elements are compared and sorted. The same process goes on for the remaining elements, thereby sorting them. In the main function, the array is defined, and ‘shell_sort’ function is called by passing this array as a parameter.

raja
Published on 14-Sep-2020 11:56:42
Advertisements