what is insertion sort

11 months ago 37
Nature

Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time by comparisons

. It works similarly to the way you sort playing cards in your hands

. The algorithm iterates through the input data, removing one element at a time, and finds the location it belongs within the sorted list, inserting it there

. It repeats this process until no input elements remain

. Some key characteristics of insertion sort include:

  • Simple implementation : Insertion sort can be implemented in a few lines of code
  • Efficient for small data sets : It is efficient for small data sets, but less efficient on large lists than more advanced algorithms like quicksort, heapsort, or merge sort
  • Adaptive : Insertion sort is adaptive, meaning it is efficient for data sets that are already partially sorted
  • In-place sorting : Yes, insertion sort is an in-place sorting algorithm
  • Stable : Insertion sort is a stable sorting algorithm

The algorithm works as follows:

  1. Start at the left-most element of the array and invoke Insert to insert each element encountered into its correct position
  1. At each iteration, remove one element from the input data and find the location it belongs within the sorted list
  1. Insert the element at the found location
  1. Repeat until no input elements remain

Insertion sort is particularly useful when the data set is already sorted or when dealing with small data sets

. However, it is less efficient than other sorting algorithms like heap sort, quick sort, and merge sort when dealing with large data sets