00:00

Insertion Sort in Java

Sorting is the process of arranging a list of unsorted data in a particular order, either ascending or descending. Sort algorithms play a very crucial role for organizing unsorted data and facilitating efficient searching, retrieval, and analysis.

Every sorting algorithm has a unique approach for sorting the data; these sorting algorithms are used according to the specific requirements of the problem, including data size, structure, and distribution, as well as time and space constraints.

In this tutorial, we are going to learn all about Insertion Sort in Java.

Java program for implementation of Insertion Sort

InsertionSortExample.java
public class InsertionSortExample {
  /* Function to sort an array using insertion sort technique */
  static void sortArray(int array[]) {
    for (int i = 1; i < array.length; ++i) {
      int key = array[i];
      int j = i - 1;

      /*
        * Move elements of array[0..i-1], that are greater than key,
        * to one position ahead of their current position
        */
      while (j >= 0 && array[j] > key) {
        array[j + 1] = array[j];
        j = j - 1;
      }
      array[j + 1] = key;
    }
  }

  // A function to print an array
  static void printArray(int array[]) {
    for (int i = 0; i < array.length; ++i)
      System.out.print(array[i] + " ");

    System.out.println();
  }

  public static void main(String args[]) {
    // Create an array
    int array[] = { 40, 70, 90, 20, 80, 100, 60, 10, 30, 50 };

    System.out.println("Created array elements: ");
    // Printing created array elements
    printArray(array);

    // Calling a method to sort an array
    sortArray(array);

    System.out.println("\nSorted array elements: ");
    // Printing sorted array elements
    printArray(array);
  }
}
Output
Created array elements:
40 70 90 20 80 100 60 10 30 50

Sorted array elements:
10 20 30 40 50 60 70 80 90 100