Let’s learn insertion sort java code.

## Insertion sort java

Insertion sort sorts elements the way in which we sort playing cards. This sort can be fast when used with smaller arrays.

Given an array of elements, let’s sort them in increasing order. So let’s look at sample list of integer elements. We have an array of six elements that we want to sort.

**Insertion sort algorithm java:**

Insertion sort iteration starts at index 1 which is 80. So we will set our key value x = 80.

Now our first comparison is to the element which is to the left of the key value, that is, 50.

Now, is x < 50? In other words, is 80 < 50? No. So, 80 is going to stay where it is.

Then we will look at index 2 in the array which is 10. We will assign key value x = 10. Now, is x < 80? Yes it is, 10 < 80. So swap 80 and 10.

Key does not change though. “x” value is still 10. So our next comparison, is 10 < 50? Yes. Swap 50 and 10.

So we are going to jump our pointer to index 3 which is 30.

So, we set our key value x = 30. Now, is x < 80? Yes it is, swap 30 and 80. Next comparison, is 30 < 50? Yes, swap those two numbers.

Next comparison, is 30 < 10? No it’s not, so we are done sorting upto index 2.

So the values to the left of 80 are all smaller. Our next element in the array is 90, we set x = 90.

Now, is x < 80? No. Here all the elements to the left of number 80 are smaller than 80 and sorted.

So we move on to index 5 which is 60. We set key value x = 60.

Now, is 60 < 90? Yes it is, swap them. Next comparison, is 60 < 80? Yes it is, swap 60 and 80.

We have our sorted array (as shown in above figure). Here’s the insertion sort program in java.

### Insertion program

public class InsertionSortExample { public void sort(int[] arrNum) { int number = arrNum.length; for(int a = 1; a < number; ++a) { int keyValue = arrNum[a]; int b = a - 1; while(b >= 0 && arrNum[b] > keyValue) { arrNum[b + 1] = arrNum[b]; b = b - 1; } arrNum[b + 1] = keyValue; } } static void displayArray(int[] arrNum) { int num = arrNum.length; for(int a = 0; a < num; ++a) { System.out.print(arrNum[a] + " "); } System.out.println(); } public static void main(String[] args) { int[] arrInput = { 50, 80, 10, 30, 90, 60 }; InsertionSortExample obj = new InsertionSortExample(); obj.sort(arrInput);displayArray(arrInput); } }

**Output:**

10 30 50 60 80 90

**Time complexity**

It’s O(n*2). Insertion sort algorithm takes more time if elements in the array is in reverse order.

**Auxiliary space:** O(1)

**Best performance:** O(n) comparison and O(1) swap.

**Worst performance:** O(n²) comparison and swap.

**Average performance:** O(n²) comparison and swap.