×

Insertion Sort in Java

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.

Algorithm

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

 for (i ? 1; i < size(arr);)
    currentEle ? arr[i]
    j ? i - 1
    while j >= 0 and arr[j] > currentEle
        arr[j + 1] ? arr[j]
        j ? j - 1
    finish while
    arr[j + 1] ? currentEle
    i ? i + 1
end for loop 

Insertion Sort Java Program

The following Java program implements the insertion sort.

FileName: InsertionSortExample.java

 public class InsertionSortExample
{
// method implementing the insertion sort algorithm
static void insertionSort(int a[], int size)
{
    // outer loop iterates over elements of the array
    // starting from the second index and goes till the last index
    for(int i = 1; i < size; i++)
    {
        // j only points the predecessor elements
        int j = i - 1;
        // current element
        int currentEle = a[i];
        // while loop to do the comparison
        // with the  predecessors
        while(j >= 0 && a[j] > currentEle)
        {
            // swapping predecessor elements that
            // are greater than the current element
            a[j + 1] = a[j];
            // checking for other predecessors
            j = j - 1;
        }
        // positioning the current element
        // at its correct position
        a[j + 1] = currentEle;
    }
}
// main method
public static void main(String argvs[])
{
    // given input array
    int a[] = {67, 78, 34, 12, 30, 6, 9, 21};
    // calculating size of the array
    int size = a.length;
    System.out.println("The array before sorting is: ");
    for(int i = 0; i < size; i++)
    {
       System.out.print(a[i] + " ");
    }
    System.out.println("\n") 
    // invoking method insertionSort()
    insertionSort(a, size);
    System.out.println("The array after sorting is: ");
    // displaying the sorted array
    for(int i = 0; i < size; i++)
    {
        System.out.print(a[i] + " ");
    }
}
} 

Output:

 The array before sorting is:
67 78 34 12 30 6 9 21
The array after sorting is:
6 9 12 21 30 34 67 78 

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.

Conclusion

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.


Related Topics

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java LDAP Authentication

WHAT IS LDAP? Clients can communicate with directory services by sending requests and receiving responses using the Lightweight Directory Access Protocol (LDAP). The term "LDAP server" refers to a directory service...

7 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.