Saturday 14 October 2017

Java Code for insertion sort using recursion

Problem:

We can express insertion sort as a recursive procedure as follows. In order to sort
A[1.. n], we recursively sort A[1.. n-1] and then insert A[n] into the sorted array
A[1.. n- 1]. Write a recurrence for the running time of this recursive version of
insertion sort.

Solution:

package com.basics;

import java.util.Arrays;
import java.util.Scanner;

public class InsertionSortUsingRecursion {

static int[] array;
int arrayLimit;

public static void main(String[] args) {
InsertionSortUsingRecursion insertionSort = new InsertionSortUsingRecursion();
insertionSort.initializeTheArrays();
System.out.println("Before sorting an array is " + Arrays.toString(array));
insertionSort.insertionSort(array, array.length);
System.out.println("After sorting an array is " + Arrays.toString(array));

}

public void initializeTheArrays(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the array limit");
arrayLimit = scanner.nextInt();
array = new int[arrayLimit];
System.out.println("enter the array elements");
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}
scanner.close();
}

public void insertionSort(int[] arr, int n){
        if (n <= 1)
            return;
     
        insertionSort( arr, n-1 );
     
        int last = arr[n-1];
        int j = n-2;
     
        while (j >= 0 && arr[j] > last)
        {
            arr[j+1] = arr[j];
            j--;
        }
        arr[j+1] = last;
}
}


Output:

enter the array limit
5
enter the array elements
enter the element
12
enter the element
3
enter the element
44
enter the element
1
enter the element
2344
Before sorting an array is [12, 3, 44, 1, 2344]
After sorting an array is [1, 3, 12, 44, 2344]


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...