Insertion Sort in Java

Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element, i.e., take only one element at a time without considering the whole list or array.

The insertion sort virtually divides the array into two halves, one is sorted, and another is un-sorted. Elements from the unsorted part are taken one by one and placed at their proper position in the sorted part. Thus, over a period of time size of sorted part increases and eventually becomes equal to size of the input array or list.


Step 1: Iterate from the second element (arr[1]) to the last element of the array (arr[n-1])

Step 2: Make the comparison of the current element to its predecessors. The comparison should continue till the beginning of the array or till a predecessor element is smaller or equal to the current element.

Step 3: Shift the predecessor elements that are greater than the current element to the right by one position. It is done to make the space positioning the current element to its appropriate location.
Step 4: Shift the current element to its appropriate location.

Pseudo Code

Insertion Sort Java Program

The following Java program implements the insertion sort.



Explanation: In the above program, two pointers approach is used to sort the elements. The outer loop variable i points to the current element whose correct position is to be determined. The inner while loop does the determination of the appropriate position of the current element. At last, the current element is placed at their correct position. The following diagram illustrates the same.

Insertion Sort in Java

Analysis of the Insertion Sort

Insertion sort is a stable sorting algorithm. However, the insertion sort is not as quick as merge sort or quick sort. Because it usage nested for-loop to do the sorting (see code).

Time Complexity

When a sorted array is provided as the input, the inner while never comes into action, and hence time complexity, which is also the best case for insertion sort, turns out to be O(n), where n is the size of the array. In the average or worst case, the while loop also comes into the picture, and hence time complexity becomes O(n2).

Space Complexity

Similar to bubble sort, insertion sort is also an in-place sorting. The space complexity of the insertion sort is O(1), i.e., constant space for sorting any input array.


Because of the O(n2) time complexity in the average or worst case, the algorithm is not suitable for dealing with large input arrays or lists. If the array is almost sorted and few swaps can make the array sorted, we can go with insertion sort. Also, for arrays of smaller size, insertion sort can be used.

Pin It on Pinterest

Share This