Site icon

Sort an integer array using insertion sort algorithm in java (with example)

What is insertion sort algorithm?

Properties of insertion sort algorithm

Algorithm: sort an array using insertion sort in java

  1. Given an unsorted array and let length denotes number of elements in an array.
  2. We will use two loops to sort an array.
  3. Start iterating through the array
    • Outer loop iterate from 1 to length – 1 and let it be iArray.
    • Get the current element at iArray index (Let it be dataToBeInserted)
    • Assume elements on the left of iArray as sorted
      • Index of iSortedArray = iArray -1
      • iSortedArray signify the sorted Array
    • Start another lopp, to insert a element to a sorted array
      • Iterate through sorted array (iSortedArray index)
      • Compare dataToBeInserted with each element in a sorted array
        • Find and create a space, where element should be inserted.
    • Insert the element at index calculated earlier.
  4. Once we are out of loop, we will get sorted array.

Performance analysis of insertion sort algorithm

S. No.Cases  Complexity
1Best case O(n)
2Average case O(n^2)
3Worst case O(n^2)

Program – sort  an integer array using insertion sort algorithm in java

package org.learn.arrays;

import java.util.Arrays;

public class InsertionSort {

	public static void main(String[] args) {
		int[] example1 = { 10, 7, 25, 20, 12, 9 };
		System.out.println("Unsorted array is : " + Arrays.toString(example1));
		insertionSort(example1);

		int[] example2 = { 5, 4, 3, 2, 1, 0 };
		System.out.println("\nUnsorted array is : " + Arrays.toString(example2));
		insertionSort(example2);
	}

	private static void insertionSort(int[] inputArray) {
		
		int length = inputArray.length;
		int iArray = 1, iSortedArray, dataToBeInserted;
		
		//Start iterating the array from 1 to length
		while (iArray < length) { 
			iSortedArray = iArray - 1; dataToBeInserted = inputArray[iArray]; 
			
			//Perform insertion sort in this while loop		
			while (iSortedArray >= 0 && dataToBeInserted < inputArray[iSortedArray]) {
				//Create a space  in input array by shifting elements on right
				inputArray[iSortedArray + 1] = inputArray[iSortedArray];
				iSortedArray--;
			}
			
			//Put the element in space created by above while loop
			inputArray[iSortedArray + 1] = dataToBeInserted;
			iArray++;
		}
		
		System.out.println("Sorted Array is :"+ Arrays.toString(inputArray));
	}
}

Output – sort an integer array using insertion sort algorithm in java

Unsorted array is : [10, 7, 25, 20, 12, 9]
Sorted Array is   : [7, 9, 10, 12, 20, 25]

Unsorted array is : [5, 4, 3, 2, 1, 0]
Sorted Array is   : [0, 1, 2, 3, 4, 5]
Exit mobile version