Given an array of positive integers and two indices l and r, sort all elements outside the subarray arr[l..r] in ascending order. The elements within the given subarray must remain unchanged.
- The elements outside the specified subarray can be extracted, sorted, and placed back into their original positions.
- The approach takes O(n log n) time and O(n) auxiliary space.
Examples:
Input:
arr[] = {10, 4, 11, 7, 6, 20},l = 1, r = 3
Output:6 4 11 7 10 20Input:
arr[] = {5, 4, 3, 12, 14, 9},l = 1, r = 2
Output:5 4 3 9 12 14The elements between indices
landrremain unchanged, while all other elements are sorted.
Approache
The array can be rearranged by collecting the elements outside the given subarray, sorting them, and placing them back into their original positions.
Steps
- Store all elements before index l and after index r in an auxiliary array.
- Sort the auxiliary array in ascending order.
- Traverse the original array again.
- Skip the elements from index l to r.
- Replace the remaining elements with the sorted elements from the auxiliary array.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to sort elements except the subarray [l, r]
void sortExceptRange(vector<int>& arr, int l, int r)
{
int n = arr.size();
vector<int> temp;
// Store elements outside the given range
for (int i = 0; i < n; i++)
{
if (i < l || i > r)
temp.push_back(arr[i]);
}
// Sort the selected elements
sort(temp.begin(), temp.end());
// Place sorted elements back
int j = 0;
for (int i = 0; i < n; i++)
{
if (i < l || i > r)
arr[i] = temp[j++];
}
}
int main()
{
vector<int> arr = {5, 4, 3, 12, 14, 9};
int l = 2, r = 4;
// Sort elements except arr[l..r]
sortExceptRange(arr, l, r);
for (int x : arr)
cout << x << " ";
return 0;
}
Output
4 5 3 12 14 9
Explanation: The elements at indices 2 to 4 remain unchanged. The remaining elements 5, 4, 9 are sorted as 4, 5, 9 and placed back into their original positions, producing 4 5 3 12 14 9.