×

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

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Java Subtract Days from Current Date

Dealing with date and time in Java is not a particularly challenging operation because Java has an API for date and time that simplifies duties for developers. There are two...

3 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 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.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.