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

PythonServer Side ProgrammingProgramming

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 <= 1000000, do
      • 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 <= 1000000:
         temp_arr[val] = temp_arr[val] + 1
         val += val & -val
   ans = length * (length - 1) // 2 - ans
   return ans

print(solve([4, 5, 3, 1, 2]))

Input

[4, 5, 3, 1, 2]

Output

8
raja
Updated on 09-Oct-2021 11:07:25

Advertisements