![]() |
VOOZH | about |
Given an array arr[] of length n + m, where the first n elements are already sorted, sort the whole array.
Examples:
Input: arr[] = [1, 3, 6, 19, 11, 16], m = 3
Output: [1, 3, 6, 11, 16, 19]
Explanation: Sorting last 3 elements [19, 11, 16] and merging with first 3 sorted elements [1, 3, 6] gives [1, 3, 6, 11, 16, 19].Input: arr[] = [1, 3, 5, 2, 6, 4], m = 3
Output: [1, 2, 3, 4, 5, 6]
Explanation: Sorting the last 3 elements [2,6,4] and merging with the first 3 sorted elements [1, 3, 5] gives [1, 2, 3, 4, 5, 6].
Table of Content
The simplest idea is to ignore the fact that first n elements are already sorted and just sort the entire array using any standard sorting algorithm. This is simple but does not take advantage of the pre-sorted first n elements.
1 3 6 11 16 19
The idea is to take advantage of the fact that first n elements are already sorted. Sort only the last m elements and then merge them with the first n sorted elements using two pointers from right to left - this avoids any extra O(n) space by filling the result from the end of the array.
1 3 6 11 16 19