VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-an-array-having-first-n-elements-sorted-and-last-m-elements-are-unsorted/

⇱ Sort an Array with a Prefix Already Sorted - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort an Array with a Prefix Already Sorted

Last Updated : 16 Jun, 2026

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].

[Naive Approach] Sorting Entire Array - O((n+m) log(n+m)) Time and O(1) Space

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.


Output
1 3 6 11 16 19

[Expected Approach] Sort Last M and Merge - O(n + m log m) Time and O(m) Space

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.


Output
1 3 6 11 16 19


Comment
Article Tags: