C++ Program for Sorting array except elements in a subarray

Last Updated : 31 Aug, 2026

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 20

Input: arr[] = {5, 4, 3, 12, 14, 9}, l = 1, r = 2
Output: 5 4 3 9 12 14

The elements between indices l and r remain 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

  1. Store all elements before index l and after index r in an auxiliary array.
  2. Sort the auxiliary array in ascending order.
  3. Traverse the original array again.
  4. Skip the elements from index l to r.
  5. Replace the remaining elements with the sorted elements from the auxiliary array.
C++
#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.

Comment