Open In App

Sort the array in a given index range

Last Updated : 13 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N integers and an index range [a, b]. The task is to sort the array in this given index range i.e., sort the elements of the array from arr[a] to arr[b] while keeping the positions of other elements intact and print the modified array. 

Note: There is no relation between a and b i.e., a can be less than, equal to or greater than b. Also, 0 ? a, b < N

Examples: 

Input: arr[] = {7, 8, 4, 5, 2}, a = 1, b = 4 
Output: 7 2 4 5 8 
For the index range [1, 4] we get the elements 8, 4, 5 and 2 
On sorting these elements we get 2, 4, 5 and 8. 
So the array is modified as {7, 2, 4, 5, 8}

Input: arr[] = {20, 10, 3, 8}, a = 3, b = 1 
Output: 20 3 8 10 

Approach: 

  1. Make a temporary array of the elements for the given index range of the array.
  2. Sort this temporary array.
  3. Now modify the original array with these sorted elements of temporary array for the given index range.

Below is the implementation of the above approach:  

C++




// C++ program to sort the
// array in a given index range
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort the elements of the array
// from index a to index b
void partSort(int arr[], int N, int a, int b)
{
    // Variables to store start and
    // end of the index range
    int l = min(a, b);
    int r = max(a, b);
 
    // Temporary array
    int temp[r - l + 1];
    int j = 0;
    for (int i = l; i <= r; i++) {
        temp[j] = arr[i];
        j++;
    }
 
    // Sort the temporary array
    sort(temp, temp + r - l + 1);
 
    // Modifying original array with
    // temporary array elements
    j = 0;
    for (int i = l; i <= r; i++) {
            arr[i] = temp[j];
            j++;
    }
 
    // Print the modified array
    for (int i = 0; i < N; i++) {
            cout << arr[i] << " " ;
        }
         
}
 
 
// Driver code
int main()
{
    int arr[] = { 7, 8, 4, 5, 2 } ;
    int a = 1 ;
    int b = 4;
 
    // length of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    partSort(arr, N, a, b);
    return 0;
}
// This code is contributed by Ryuga


Java




// Java program to sort the array in a given index range
import java.io.*;
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to sort the elements of the array
    // from index a to index b
    static void partSort(int[] arr, int N, int a, int b)
    {
        // Variables to store start and end of the index range
        int l = Math.min(a, b);
        int r = Math.max(a, b);
 
        // Temporary array
        int[] temp = new int[r - l + 1];
        int j = 0;
        for (int i = l; i <= r; i++) {
            temp[j] = arr[i];
            j++;
        }
 
        // Sort the temporary array
        Arrays.sort(temp);
 
        // Modifying original array with temporary array elements
        j = 0;
        for (int i = l; i <= r; i++) {
            arr[i] = temp[j];
            j++;
        }
 
        // Print the modified array
        for (int i = 0; i < N; i++) {
            System.out.print(arr[i] + " ");
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        int[] arr = { 7, 8, 4, 5, 2 };
        int a = 1, b = 4;
 
        // length of the array
        int N = arr.length;
 
        partSort(arr, N, a, b);
    }
}


Python3




# Python 3 program to sort the
# array in a given index range
 
# Function to sort the elements of
# the array from index a to index b
def partSort(arr, N, a, b):
     
    # Variables to store start and
    # end of the index range
    l = min(a, b)
    r = max(a, b)
 
    # Temporary array
    temp = [0 for i in range(r - l + 1)]
    j = 0
    for i in range(l, r + 1, 1):
        temp[j] = arr[i]
        j += 1
     
    # Sort the temporary array
    temp.sort(reverse = False)
 
    # Modifying original array with
    # temporary array elements
    j = 0
    for i in range(l, r + 1, 1):
            arr[i] = temp[j]
            j += 1
 
    # Print the modified array
    for i in range(0, N, 1):
            print(arr[i], end = " ")
 
# Driver code
if __name__ == '__main__':
    arr = [7, 8, 4, 5, 2]
    a = 1
    b = 4
 
    # length of the array
    N = len(arr)
 
    partSort(arr, N, a, b)
 
# This code is contributed by
# Surendra_Gangwar


C#




// C# program to sort the array in a given index range
using System;
class GFG {
 
    // Function to sort the elements of the array
    // from index a to index b
    static void partSort(int[] arr, int N, int a, int b)
    {
        // Variables to store start and end of the index range
        int l = Math.Min(a, b);
        int r = Math.Max(a, b);
 
        // Temporary array
        int[] temp = new int[r - l + 1];
        int j = 0;
        for (int i = l; i <= r; i++) {
            temp[j] = arr[i];
            j++;
        }
 
        // Sort the temporary array
        Array.Sort(temp);
 
        // Modifying original array with temporary array elements
        j = 0;
        for (int i = l; i <= r; i++) {
            arr[i] = temp[j];
            j++;
        }
 
        // Print the modified array
        for (int i = 0; i < N; i++) {
            Console.Write(arr[i] + " ");
        }
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 7, 8, 4, 5, 2 };
        int a = 1, b = 4;
 
        // length of the array
        int N = arr.Length;
 
        partSort(arr, N, a, b);
    }
}
// This code is contributed by anuj_67


PHP




<?php
# PHP program to sort the
# array in a given index range
 
 
 
// Function to sort the elements of the array
// from index a to index b
function partSort( $arr, $N, $a, $b)
{
    // Variables to store start and
    // end of the index range
    $l = min($a, $b);
     $r = max($a, $b);
 
    // Temporary array
    $temp = array();
    $j = 0;
    for ($i = $l; $i <= $r; $i++) {
        $temp[$j] = $arr[$i];
        $j++;
    }
 
    // Sort the temporary array
    sort($temp);
 
    // Modifying original array with
    // temporary array elements
    $j = 0;
    for ($i = $l; $i <= $r; $i++) {
            $arr[$i] = $temp[$j];
            $j++;
    }
 
    // Print the modified array
    for ($i = 0; $i < $N; $i++) {
            echo $arr[$i]." " ;
        }
         
}
 
 
 
    $arr = array( 7, 8, 4, 5, 2 ) ;
    $a = 1 ;
    $b = 4;
 
    // length of the array
    $N = count($arr);
 
    partSort($arr, $N, $a, $b);
    //This code is contributed by 29AjayKumar
    ?>


Javascript




<script>
    // Javascript program to sort the array in a given index range
     
    // Function to sort the elements of the array
    // from index a to index b
    function partSort(arr, N, a, b)
    {
        // Variables to store start and end of the index range
        let l = Math.min(a, b);
        let r = Math.max(a, b);
  
        // Temporary array
        let temp = new Array(r - l + 1);
        temp.fill(0);
        let j = 0;
        for (let i = l; i <= r; i++) {
            temp[j] = arr[i];
            j++;
        }
  
        // Sort the temporary array
        temp.sort(function(a, b){return a - b});
  
        // Modifying original array with temporary array elements
        j = 0;
        for (let i = l; i <= r; i++) {
            arr[i] = temp[j];
            j++;
        }
  
        // Print the modified array
        for (let i = 0; i < N; i++) {
            document.write(arr[i] + " ");
        }
    }
     
    let arr = [ 7, 8, 4, 5, 2 ];
    let a = 1, b = 4;
 
    // length of the array
    let N = arr.length;
 
    partSort(arr, N, a, b);
 
</script>


Output

7 2 4 5 8 

Complexity Analysis:

  • Time Complexity: O(nlog(n))
  • Auxiliary Space: O(n)

Below is a direct solution using Arrays.sort() 

C++




// C++ program to sort the array in a given index range
#include<bits/stdc++.h>
using namespace std;
 
    // Function to sort the elements of the array
    // from index a to index b
    void partSort(int arr[], int N, int a, int b)
    {
        // Variables to store start and end
        // of the index range
        int l = min(a, b);
        int r = max(a, b);
         
        vector<int> v(arr, arr + N);
 
        // Sort the subarray from arr[l] to
        // arr[r]
        sort(v.begin() + l, v.begin() + r + 1);
 
        // Print the modified array
        for (int i = 0; i < N; i++)
            cout << v[i] << " ";
    }
 
    // Driver code
    int main()
    {
        int arr[] = { 7, 8, 4, 5, 2 };
        int a = 1, b = 4;
        int N = sizeof(arr)/sizeof(arr[0]);
        partSort(arr, N, a, b);
    }
     
// This code is contributed by
// Sanjit_Prasad


Java




// Java program to sort the array in a given index range
import java.io.*;
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to sort the elements of the array
    // from index a to index b
    static void partSort(int[] arr, int N, int a, int b)
    {
        // Variables to store start and end
        // of the index range
        int l = Math.min(a, b);
        int r = Math.max(a, b);
 
        // Sort the subarray from arr[l] to
        // arr[r]
        Arrays.sort(arr, l, r + 1);
 
        // Print the modified array
        for (int i = 0; i < N; i++)
            System.out.print(arr[i] + " ");
    }
 
    // Driver code
    public static void main(String args[])
    {
        int[] arr = { 7, 8, 4, 5, 2 };
        int a = 1, b = 4;
        int N = arr.length;
        partSort(arr, N, a, b);
    }
}


Python3




# Python3 program to sort the
# array in a given index range
 
# Function to sort the elements of
# the array from index a to index b
def partSort(arr, N, a, b):
     
    # Variables to store start and
    # end of the index range
    l = min(a, b)
    r = max(a, b)
 
    arr = (arr[0 : l] +
    sorted(arr[l : r + 1]) +
           arr[r : N])
 
    # Print the modified array
    for i in range(0, N, 1):
            print(arr[i], end = " ")
 
# Driver code
if __name__ == '__main__':
     
    arr = [ 7, 8, 4, 5, 2 ]
    a = 1
    b = 4
 
    # Length of the array
    N = len(arr)
 
    partSort(arr, N, a, b)
 
# This code is contributed by grand_master


C#




// C# program to sort the array in a given index range
using System;
 
class GFG {
 
    // Function to sort the elements of the array
    // from index a to index b
    static void partSort(int[] arr, int N, int a, int b)
    {
        // Variables to store start and end
        // of the index range
        int l = Math.Min(a, b);
        int r = Math.Max(a, b);
 
        // Sort the subarray from arr[l] to
        // arr[r]
        Array.Sort(arr, l, r);
 
        // Print the modified array
        for (int i = 0; i < N; i++)
            Console.Write(arr[i] + " ");
    }
 
    // Driver code
    static void Main()
    {
        int[] arr = { 7, 8, 4, 5, 2 };
        int a = 1, b = 4;
        int N = arr.Length;
        partSort(arr, N, a, b);
    }
}
 
// This code is contributed by mits


Javascript




<script>
// javascript program to sort the array in a given index range
// Function to sort the elements of the array
// from index a to index b
function swap(arr, xp, yp)
{
    var temp = arr[xp];
    arr[xp] = arr[yp];
    arr[yp] = temp;
}
    function partSort(arr , N , a , b)
    {
     
        // Variables to store start and end
        // of the index range
        var l = Math.min(a, b);
        var r = Math.max(a, b);
 
        // Sort the subarray from arr[l] to
        // arr[r]
        //.sort(arr, l, r + 1);
        var i, j;
        for (i = l; i < r + 1 + 1; i++)
        {
            for (j = l; j < r - i + 1; j++)
            {
        if (arr[j] > arr[j + 1])
        {
        swap(arr, j, j + 1);
           
        }
    }
   
}
 
        // Print the modified array
        for (i = 0; i < N; i++)
            document.write(arr[i] + " ");
    }
 
    // Driver code
        var arr = [ 7, 8, 4, 5, 2 ];
        var a = 1, b = 4;
        var N = arr.length;
        partSort(arr, N, a, b);
 
// This code is contributed by gauravrajput1
</script>


Output

7 2 4 5 8 

Complexity Analysis:

  • Time Complexity: O(nlog(n))
  • Auxiliary Space: O(n)


Similar Reads

Minimum index i such that all the elements from index i to given index are equal
Given an array arr[] of integers and an integer pos, the task is to find the minimum index i such that all the elements from index i to index pos are equal. Examples: Input: arr[] = {2, 1, 1, 1, 5, 2}, pos = 3 Output: 1 Elements in index range [1, 3] are all equal to 1. Input: arr[] = {2, 1, 1, 1, 5, 2}, pos = 5 Output: 5 Brute Force Approach: A br
12 min read
Sort Array such that smallest is at 0th index and next smallest it at last index and so on
Given an array, arr[] of N integers, the task is to rearrange the array elements such that the smallest element is at the 0th position, the second smallest element is at the (N-1)th position, the third smallest element at 1st position, 4th smallest element is at the (N-2)th position, and so on for all integers in arr[]. Examples: Input: arr[] = {10
12 min read
Queries for elements having values within the range A to B in the given index range using Segment Tree
Given an array arr[] of N elements and two integers A to B, the task is to answer Q queries each having two integers L and R. For each query, the task is to find the number of elements in the subarray arr[L...R] which lies within the range A to B (both included). Examples: Input: arr[] = {7, 3, 9, 13, 5, 4}, A=4, B=7 query = { 1, 5 } Output: 2 Expl
13 min read
Farthest index that can be reached from the Kth index of given array by given operations
Given an array arr[] consisting of N integers and three integers X, Y, and K, the task is to find the farthest index that can be reached by the following operations: If arr[i] ? arr[i + 1]: Move from index i to i + 1.If arr[i] &lt; arr[i+1]: Either decrement X by 1 if the value of X &gt; 0 or decrement Y by (arr[i + 1] - arr[i]) if the value of Y
7 min read
Queries for number of distinct elements from a given index till last index in an array
Given a array ‘a[]’ of size n and number of queries q. Each query can be represented by a integer m. Your task is to print the number of distinct integers from index m to n i.e till last element of the array. Examples: Input: arr[] = {1, 2, 3, 1, 2, 3, 4, 5}, q[] = {1, 4, 6, 8} Output: 5 5 3 1 In query 1, number of distinct integers in a[0...7] is
6 min read
Count pairs in given Array having sum of index and value at that index equal
Given an array arr[] containing positive integers, count the total number of pairs for which arr[i]+i = arr[j]+j such that 0≤i&lt;j≤n-1. Examples: Input: arr[] = { 6, 1, 4, 3 }Output: 3Explanation: The elements at index 0, 2, 3 has same value of a[i]+i as all sum to 6 {(6+0), (4+2), (3+3)}. Input: arr[] = { 8, 7, 6, 5, 4, 3, 2, 1 }Output: 28 Naive
8 min read
Comparison among Bubble Sort, Selection Sort and Insertion Sort
Bubble Sort, Selection Sort, and Insertion Sort are simple sorting algorithms that are commonly used to sort small datasets or as building blocks for more complex sorting algorithms. Here's a comparison of the three algorithms: Bubble Sort:Time complexity: O(n^2) in the worst and average cases, O(n) in the best case (when the input array is already
15 min read
Sort M elements of given circular array starting from index K
Given a circular array arr[] of size N and two integers K and M, the task is to sort M array elements starting from the index K. Examples: Input: arr[] = {4, 1, 6, 5, 3}, K = 2, M = 3Output: 4 1 3 5 6Explanation: After sorting 3 array elements starting from index 2 modifies arr[] to {4, 1, 3, 5, 6}. Input: arr[] = {67, 2, 9, 7, 1}, K = 4, M = 3Outp
13 min read
Sort number line given as Array by moving an element at ith index by i steps to right
Given an array arr[] of N integers, the task is to find the minimum number of the moves needed to sort the array in ascending order by moving an element at ith index by i steps to the right in a single move. Note: In a step, two numbers can lie in the same position. Examples: Input: N = 4, arr[] = {1, 2, 7, 4}Output: 1Explanation: Moving the elemen
7 min read
Find element at given index after given range reversals
An array consisting of N elements is given. There are several reversals we do in unique ranges[L..R]. The task is to print the element at given index. Examples: Input : arr[] : 10 20 30 40 50ranges[] = {{1, 4}, {0, 2}}Query Index = 1Output : 50Explanation : Reverse range[1..4] : 10 50 40 30 20Reverse range[0..2] : 40 50 10 30 20So we have 50 at ind
10 min read