Sorting — Insertion sort- Interview Preparation — HackerRank

Amber Ivanna Trujillo
2 min readOct 26, 2020
  • Initialization — The subarray starts with the first element of the array, and it is (obviously) sorted to begin with. Its just one element and one element is sorted.
  • Maintenance — Each iteration of the loop expands the subarray to one more element on the right, but keeps the sorted property.
  • An element gets inserted into the array only when it is greater than the element to its left. Since the elements to its left have already been sorted, it means is greater than all the elements to its left, so the array remains sorted.
  • Termination — The code will terminate after has reached the last element in the array, which means the sorted subarray has expanded to encompass the entire array. The array is now fully sorted.

Sample Input

6
1 4 3 5 6 2

Sample Output

1 4 3 5 6 2 
1 3 4 5 6 2
1 3 4 5 6 2
1 3 4 5 6 2
1 2 3 4 5 6

Explanation

Example : Sort array 1 4 3 5 6 2

Intialization : Skip testing 1 against itself at position 0 . It is sorted.
Maintenance or Iteration :

  1. Test position 1 against position 0: a[1] > a[0] (4>1, no more to check, no change. Array is 1 4 3 5 6 2
  2. Test position 2 against positions 1 and 0:
  • 3<4, new position may be 1. Keep checking.
  • 3>1, so insert 3 at position and move others to the right.
  • Array is 1 3 4 5 6 2

3. Test position 3 against positions 2,1,0(as necessary): no change.

  • Array is 1 3 4 5 6 2

4. Test position 4 against positions 3,2,1,0: no change.

  • Array is 1 3 4 5 6 2

5. Test position 5 against positions 4,3,2,1,0, insert 2 at position 1and move others to the right.

  • Array is 1 2 3 4 5 6

Code: Python 3

// Assuming we input n = total elements and
// all elements space separated as inputs to the program.
n = int(input())
l = list(map(int, input().rstrip().split()))
n = len(l)for i in range(1,n):
val = l[i]
j = i - 1
while(j >= 0 and l[j]>= val):
l[j+1] = l[j]
j = j-1
l[j+1] = val print(*l)

Analysis:

  1. It is a simple sorting algorithm that works well with small or mostly sorted data. However, it takes a long time to sort large unsorted data.

--

--

Amber Ivanna Trujillo

I am Executive Data Science Manager. Interested in Deep Learning, LLM, Startup, AI-Influencer, Technical stuff, Interviews and much more!!!