Java Program for Recursive Insertion Sort

JavaObject Oriented ProgrammingProgramming

Following is the Java Program for Recursive Insertion Sort −

Example

 Live Demo

import java.util.Arrays;
public class Demo{
   static void recursive_ins_sort(int my_arr[], int arr_len){
      if (arr_len <= 1)
         return;
      recursive_ins_sort( my_arr, arr_len-1 );
      int last = my_arr[arr_len-1];
      int j = arr_len-2;
      while (j >= 0 && my_arr[j] > last){
         my_arr[j+1] = my_arr[j];
         j--;
      }
      my_arr[j+1] = last;
   }
   public static void main(String[] args){
      int my_arr[] = {11, 23, 67, 83, 42, 11, 0};
      recursive_ins_sort(my_arr, my_arr.length);
      System.out.println("The array elements after implementing insertion sort is ");
      System.out.println(Arrays.toString(my_arr));
   }
}

Output

The array elements after implementing insertion sort is
[0, 11, 11, 23, 42, 67, 83]

A class named Demo contains the static recursive function for insertion sort. This function takes the array and its length as parameters. Here, several conditions are checked. If the length of the array is less than 1, it is returned as it is. Otherwise, the elements of the array are sorted by reducing the size of the array again and again by reducing the size of the array.

The last element of the array will be placed in the right position and another variable is used as index to check if the last element in the array is equal to that specific index element in the array. This way, the elements are placed in their right positions. If an element greater than key is encountered, it is incremented to the next position. Relevant output is displayed on the console.

raja
Published on 07-Jul-2020 11:27:16
Advertisements