Insertion sort in Java. Simple solution example. – IT Blog
IT Blog
Boris IT Expert

Insertion sort in Java. Simple solution example.

Boris~November 11, 2020 /Sorting Algorithms

In this article, we will discuss the way of the implementation of the insertion sort in Java. Because the sorting algorithm is a famous question on any technical interview, I recommend to learn it. The basic idea is to divide an array list into two parts. The left side is supposed to include sorted elements. On the right side of the current elements, we have unsorted elements. We are getting the current element with each iteration and put it in the right place on the left sorted side. And repeat this procedure until an array list is a finish.

Insertion sort of the Array List? The simple solution in Java.

Step-by-step implementation with the pictures and explanations. The most apparent solution below:

//Looping the array
        for (int i = 0; i < array.length; i++) 
//Getting as a key current element
            int current = array[i];
//Getting the element that goes BEFORE current
            int j = i - 1;
//Checking if previous element more or equal to zero to avoid go outside the array
//Checking if the current element less than previous element

            while (j >= 0 && current < array[j]) {
//Temporary variable to save previous element value for swapping
                int temporary = array[j];

//Previous element become the next (which is current)
                array[j] = current;

//Current becomes a previous
                array[current] = temporary;

 //After elements swapped we decrease the previous element to start new compare
                j--;
            }

Animation:

Full schema:

insertion sort java

Code example:

private void insertionSort() {
//Creating array of integers
        int[] array = {4,2,3,1,5};

 //Looping the array
        for (int i = 0; i < array.length; i++) {
 //Getting as a key current element
            int current = array[i];
 //Getting the element that goes BEFORE current
            int j = i - 1;

//Checking if previous element more or equal to zero to avoid go outside the array
 //Checking if the current element less than previous element

            while (j >= 0 && current < array[j]) {
 //Temporary variable to save previous element value for swapping
                int temporary = array[j];
//Previous element become the next (which is current)
                array[j] = current;
//Current becomes a previous
                array[current] = temporary;
//After elements swapped we decrease the previous element to start new compare
                j--;
            }
        }

        for (int i : array) {
            Log.d("arrayList", "-> " + i);
        }
    }

In this article, you see an example of the insertion sort in Java.

Full code and more examples in my facebook group.

Useful links:

Leave Any Questions Related To This Article Below!