We have discussed Merge sort. How to modify the algorithm so that merge works in O(1) extra space and algorithm still works in O(n Log n) time. We may assume that the input values are integers only.
Input : 5 4 3 2 1 Output : 1 2 3 4 5 Input : 999 612 589 856 56 945 243 Output : 56 243 589 612 856 945 999
For integer types, merge sort can be made inplace using some mathematics trick of modulus and division. That means storing two elements value at one index and can be extracted using modulus and division.
First we have to find a value greater than all the elements of the array. Now we can store the original value as modulus and the second value as division. Suppose we want to store arr[i] and arr[j] both at index i(means in arr[i]). First we have to find a ‘maxval’ greater than both arr[i] and arr[j]. Now we can store as arr[i] = arr[i] + arr[j]*maxval. Now arr[i]%maxval will give the original value of arr[i] and arr[i]/maxval will give the value of arr[j]. So below is the implementation on merge sort.
Sorted array 56 243 589 612 856 945 999
- Merge two BSTs with limited extra space
- Merge two sorted arrays with O(1) extra space
- Merge two BSTs with constant extra space
- Merge operations using STL in C++ | merge(), includes(), set_union(), set_intersection(), set_difference(), ., inplace_merge,
- Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
- 3-way Merge Sort
- Merge Sort
- In-Place Merge Sort
- Iterative Merge Sort
- C Program for Merge Sort
- Merge Sort using Multi-threading
- Java Program for Merge Sort
- Merge Sort for Linked Lists
- Python Program for Merge Sort
- C Program for Iterative Merge Sort
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.