Classic algorithms · 12 / 22 Exercise Medium

Insertion sort

Objective

Create a Python program that sorts a list with the insertion sort algorithm and counts the shifts it performs.

Instructions

  • Read a line with integers separated by spaces.
  • For each position i from 1 to len(list) - 1: store key = list[i] and shift to the right the previous elements that are greater than the key (each shift adds 1 to the counter); then place the key in its gap.
  • Show Result: n1 n2 ... and, on another line, Shifts: N.
Input
12 11 13 5 6
Output
Result: 5 6 11 12 13
Shifts: 7

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise