- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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]
- Related Articles
- Number of Recent Calls in Python
- Explain Merge Sort in Python
- Merge k Sorted Lists in Python
- Python Program for Merge Sort
- Using merge sort to recursive sort an array JavaScript
- C program to sort an array by using merge sort
- Python Program for Iterative Merge Sort
- Program to find out the number of shifts required to sort an array using insertion sort in python
- Merge Sorted Array in Python
- Merge Sort
- Program to merge K-sorted lists in Python
- Find minimum number of merge operations to make an array palindrome in C++
- Program to find minimum numbers of function calls to make target array using Python
- Merge sort vs quick sort in Javascript
- Python - Sort rows by Frequency of K

Advertisements