Home | Projects | Notes > Data Structures & Algorithms > Insertion Sort: T = O(n2) , S = O(1)

Insertion Sort: T = O(n2) , S = O(1)

 

Insertion Sort

Algorithm

  1. Input: An array of elements to be sorted.

  2. Loop: Start a loop that iterates from the second element to the last element of the array.

  3. Current Element: For the current iteration, store the value of the element to be inserted into the sorted portion.

  4. Inner Loop: Within the loop, iterate from the current element's position back to the beginning of the array (or until a smaller element is found).

  5. Shift and Insert: While iterating in the inner loop, if the current element is smaller than the element being compared, shift the compared element to the right to make space for the current element.

  6. Insert Current Element: Once a suitable position is found in the inner loop, insert the current element into that position.

  7. Repeat: Continue this process for each element in the array until the entire array is sorted.

Pseudo-code

L6: The order in which you write the two condition statements of the while loop is very important. Switching the order will cause a run-time error for referencing arr[-1].

 

Code