Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

Java Insertion Sort

// Java Insertion Sort
// -------------------

/* 
   Time Complexity
     Best Time Complexity:O(n)
	 Average Time Complexity:O(n^2)
	 Worst Time Complexity:O(n^2)
     
   Space Complexity
     No auxiliary space is required in Linear Search implementation.
	 Hence space complexity is:O(1)
*/

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

public class InsertionSort {
    public static int[] sort(int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            int j = i - 1; // j will point to previous element
            int k = arr[i]; // k holds the value being sorted

            while (j >= 0 && k <= arr[j]) {
                arr[j + 1] = arr[j];
                j = j - 1;
            }

            arr[j + 1] = k;

        }
        return arr; //returns the sorted array

    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int arr[] = new int[10];

        System.out.println("Enter Array Values: ");
        for (int i = 0; i < arr.length; i++) {
            arr[i] = sc.nextInt();
        }

        int a[] = new int[arr.length];

        a = Arrays.copyOf(sort(arr), arr.length); //copies the sorted array to another array

      	//sorted in ascending order
        System.out.println("Sorted Array:");
        for (int i = 0; i < a.length; i++) {
            System.out.print(+a[i] + " ");
        }
    }

}
Source by www.programiz.com #
 
PREVIOUS NEXT
Tagged: #Java #Insertion #Sort
ADD COMMENT
Topic
Name
5+4 =