Find array with k number of merge sort calls in Python


Suppose we have two numbers a and b, we have to find an array containing values in range [1, a] and requires exactly b number of calls of recursive merge sort function.

So, if the input is like a = 10, b = 15, then the output will be [3,1,4,6,2,8,5,9,10,7]

To solve this, we will follow these steps −

  • Define a function solve() . This will take left, right, array,b
  • if b < 1 or left + 1 is same as right, then
    • return
  • b := b - 2
  • mid := (left + right) / 2
  • temp := array[mid - 1]
  • array[mid-1] := array[mid]
  • array[mid] := temp
  • solve(left, mid, array, b)
  • solve(mid, right, array, b)
  • From the main method do the following −
  • if b mod 2 is same as 0, then
    • display "None"
    • return
  • array := an array of size n + 1, and fill with 0
  • array[0] := 1
  • for i in range 1 to a, do
    • array[i] := i + 1
  • b := b - 1
  • solve(0, a, array, b)
  • return array, a

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(left,right,array,b):
   if (b < 1 or left + 1 == right):
      return
   b -= 2
   mid = (left + right) // 2
   temp = array[mid - 1]
   array[mid-1] = array[mid]
   array[mid] = temp
   solve(left, mid, array, b)
   solve(mid, right, array, b)
def find_arr(a,b):
   if (b % 2 == 0):
      print("None")
      return
   array = [0 for i in range(a + 2)]
   array[0] = 1
   for i in range(1, a):
      array[i] = i + 1
   b -=1
   solve(0, a, array, b)
return array, a
a = 10
b = 15
array, size = find_arr(a, b)
print(array[:size])

Input

10,15

Output

[3, 1, 4, 6, 2, 8, 5, 9, 10, 7]

Updated on: 28-Aug-2020

55 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements