Insertion sort in Java

Insertion sort in Java

Insertion sort is an algorithm for sorting an array by iterating through the array and inserting each element into its correct position in a sorted sub-array. It works by maintaining a sorted sub-array at the beginning of the array, and inserting each element into its correct position in the sorted sub-array as it iterates through the array.




Here is an example of how you might implement insertion sort in Java: 

class InsertionSort {

  public static void sort(int[] array) {

    for (int i = 1; i < array.length; i++) {

      int current = array[i];

      int j = i - 1;

      while (j >= 0 && current < array[j]) {

        array[j + 1] = array[j];

        j--;

      }

      array[j + 1] = current;

    }

  }

}


You can then use the sort method to sort an array as follows:
int[] array = {4, 3, 2, 1};
InsertionSort.sort(array);
System.out.println(Arrays.toString(array)); // Outputs [1, 2, 3, 4]

Post a Comment

0 Comments