what is insertion sort

3 hours ago 3
Nature

Insertion sort is a simple comparison-based sorting algorithm that builds the final sorted array one element at a time. It works by iterating through the input array, taking one element at each iteration, and inserting it into its correct position within the already sorted portion of the array. This process continues until all elements are sorted

How Insertion Sort Works

  • Start with the second element (assuming the first element is already sorted).
  • Compare this element (called the "key") with the elements before it.
  • Shift all elements that are greater than the key one position to the right.
  • Insert the key into the correct position where all elements to the left are smaller or equal.
  • Repeat this process for each element until the entire array is sorted

Characteristics

  • It sorts the array in place, requiring no additional storage.
  • Best suited for small or nearly sorted arrays.
  • Has an average and worst-case time complexity of O(n2)O(n^2)O(n2), where nnn is the number of elements.
  • Runs in O(n)O(n)O(n) time if the array is already sorted.
  • Performs fewer comparisons than selection sort on average but may require more writes

Analogy

Insertion sort is often compared to sorting playing cards in your hand: you pick up one card at a time and insert it into its correct position relative to the cards already held

Summary

Insertion sort is a straightforward, intuitive sorting method that is efficient for small or partially sorted datasets but less efficient for large, unordered data compared to more advanced algorithms like quicksort or mergesort