Program to find out the number of shifts required to sort an array using insertion sort in python

Suppose we are given an array and asked to perform insertion sort on it. In insertion sort, each element in an array is shifted to its correct position in the array. We have to find out the total number of shifts required to sort an array. The total number of shifts is an integer number and if the array is already sorted, we return 0.

So, if the input is like input_array = [4, 5, 3, 1, 2], then the output will be 8

[4, 5, 3, 1, 2] = 0 shifts

[4, 5, 3, 1, 2] = 0 shifts

[3, 4, 5, 1, 2] = 2 shifts

[1, 3, 4, 5, 2] = 3 shifts

[1, 2, 3, 4, 5] = 3 shifts

total number of shifts are = 0 + 0 + 2 + 3 + 3 = 8.

To solve this, we will follow these steps −

  • length := size of input_arr
  • temp_arr := a new list of size 1000001 initialized with 0s
  • ans := 0
  • for each item in input_arr, do
    • val := item
    • while val > 0, do
      • ans := ans + temp_arr[val]
      • val := val - (val AND -val)
    • val := item
    • while val
    • temp_arr[val] := temp_arr[val] + 1
    • val := val + (val AND -val)
  • ans := length * (floor value of (length - 1) / 2) - ans
  • return ans
  • Example

    Let us see the following implementation to get better understanding −

    def solve(input_arr):
       length = len(input_arr)
       temp_arr = [0] * 1000001
       ans = 0
       for item in input_arr:
          val = item
          while val > 0:
             ans += temp_arr[val]
             val -= val & -val
          val = item
          while val 

    Input

    [4, 5, 3, 1, 2]

    Output

    8
    Updated on: 2021-10-09T11:07:25+05:30

    1K+ Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements