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 = 3
Output: 4 1 3 5 6
Explanation: 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 = 3
Output: 2 67 9 7 1
Explanation: After sorting 3 array elements starting from index 4 modifies arr[] to {2, 67, 9, 7, 1}.
Naive Approach: The idea is to swap the adjacent elements in the circular array if the elements of them are not in the correct order. Follow the steps below to solve the given problem:
- Traverse the given array arr[] over the range [0, M – 1] using the variable i.
- Traverse the array arr[] again over the range [K, K + M – 1] using the variable j and if arr[j%n] is greater than arr[(j + 1)%n] then swap the current adjacent pairs of values.
- After the above steps, print the array arr[].
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to print the circular arrayvoid printCircularArray(int arr[], int n){    // Print the array    for (int i = 0; i < n; i++) {        cout << arr[i] << " ";    }}Â
// Function to sort m elements of diven// circular array starting from index kvoid sortCircularArray(int arr[], int n,                       int k, int m){    // Traverse M elements    for (int i = 0; i < m; i++) {Â
        // Iterate from index k to k + m - 1        for (int j = k; j < k + m - 1; j++) {Â
            // Check if the next element            // in the circular array is            // less than the current element            if (arr[j % n]                > arr[(j + 1) % n]) {Â
                // Swap current element                // with the next element                swap(arr[j % n], arr[(j + 1) % n]);            }        }    }Â
    // Print the circular array    printCircularArray(arr, n);}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 4, 1, 6, 5, 3 };Â Â Â Â int K = 2, M = 3;Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â
    // Function Call    sortCircularArray(arr, N, K, M);Â
    return 0;} |
Java
// Java program for the above approachclass GFG{      // Function to print the circular arraystatic void printCircularArray(int arr[], int n){    // Print the array    for (int i = 0; i < n; i++) {        System.out.print(arr[i] + " ");    }}  // Function to sort m elements of diven// circular array starting from index kstatic void sortCircularArray(int arr[], int n,                       int k, int m){    // Traverse M elements    for (int i = 0; i < m; i++) {          // Iterate from index k to k + m - 1        for (int j = k; j < k + m - 1; j++) {              // Check if the next element            // in the circular array is            // less than the current element            if (arr[j % n]                > arr[(j + 1) % n]) {                  // Swap current element                // with the next element                int t = arr[j % n];                arr[j % n] = arr[(j + 1) % n];                arr[(j + 1) % n] = t;            }        }    }      // Print the circular array    printCircularArray(arr, n);}  // Driver Codepublic static void main (String[] args){      int[] arr = { 4, 1, 6, 5, 3 };    int K = 2, M = 3;    int N = arr.length;      // Function Call    sortCircularArray(arr, N, K, M);}}Â
// This code is contributed by susmitakundugoaldanga |
Python3
# Python3 program for the above approachÂ
# Function to print the circular arraydef printCircularArray(arr, n):         # Print the array    for i in range(n):        print(arr[i], end = " ")Â
# Function to sort m elements of diven# circular array starting from index kdef sortCircularArray(arr, n, k, m):Â
    # Traverse M elements    for i in range(m):Â
        # Iterate from index k to k + m - 1        for j in range(k, k + m - 1):Â
            # Check if the next element            # in the circular array is            # less than the current element            if (arr[j % n] > arr[(j + 1) % n]):Â
                # Swap current element                # with the next element                arr[j % n], arr[(j + 1) % n] = (arr[(j + 1) % n],                                                 arr[j % n])                     # Print the circular array    printCircularArray(arr, n)     # Driver Codeif __name__ == "__main__" :Â
    arr = [ 4, 1, 6, 5, 3 ]    K = 2    M = 3    N = len(arr)         # Function Call    sortCircularArray(arr, N, K, M)Â
# This code is contributed by AnkThon |
C#
// C# program for the above approachusing System;Â
class GFG{              // Function to print the circular array    static void printCircularArray(int []arr, int n)    {        // Print the array        for (int i = 0; i < n; i++)        {            Console.Write(arr[i] + " ");        }    }          // Function to sort m elements of diven    // circular array starting from index k    static void sortCircularArray(int []arr, int n,                           int k, int m)    {               // Traverse M elements        for (int i = 0; i < m; i++)        {                  // Iterate from index k to k + m - 1            for (int j = k; j < k + m - 1; j++)             {                      // Check if the next element                // in the circular array is                // less than the current element                if (arr[j % n]                    > arr[(j + 1) % n]) {                          // Swap current element                    // with the next element                    int t = arr[j % n];                    arr[j % n] = arr[(j + 1) % n];                    arr[(j + 1) % n] = t;                }            }        }              // Print the circular array        printCircularArray(arr, n);    }          // Driver Code    public static void Main (string[] args)    {          int[] arr = { 4, 1, 6, 5, 3 };        int K = 2, M = 3;        int N = arr.Length;              // Function Call        sortCircularArray(arr, N, K, M);    }}Â
// This code is contributed by AnkThon |
Javascript
<script>Â
// JavaScript program for the above approachÂ
// Function to print the circular arrayfunction printCircularArray(arr, n){    // Print the array    for (let i = 0; i < n; i++) {        document.write(arr[i] + " ");    }}Â
// Function to sort m elements of diven// circular array starting from index kfunction sortCircularArray(arr, n, k, m){    // Traverse M elements    for (let i = 0; i < m; i++) {Â
        // Iterate from index k to k + m - 1        for (let j = k; j < k + m - 1; j++) {Â
            // Check if the next element            // in the circular array is            // less than the current element            if (arr[j % n]                > arr[(j + 1) % n]) {Â
                // Swap current element                // with the next element                let t = arr[j % n];                arr[j % n] = arr[(j + 1) % n];                arr[(j + 1) % n] = t;            }        }    }Â
    // Print the circular array    printCircularArray(arr, n);}Â
// Driver Code    let arr = [ 4, 1, 6, 5, 3 ];    let K = 2, M = 3;    let N = arr.length;Â
    // Function Call    sortCircularArray(arr, N, K, M);     // This code is contributed by Surbhi Tyagi.Â
</script> |
4 1 3 5 6
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach:
Step-by-step approach:
- Create a new array of size M and copy the M elements starting from index K of the circular array arr[] to the new array.
- Sort the new array.
- Traverse the circular array arr[] from index K to index (K + M – 1) mod N and replace each element with the corresponding element in the sorted new array.
- If K + M is greater than N, traverse the remaining elements of the new array and replace the corresponding elements in the circular array arr[].
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>using namespace std;Â
void sortCircularArray(int arr[], int n, int k, int m) {    // Create a new array of size M and copy the     // M elements starting from index K    int* tempArr = new int[m];    for (int i = 0; i < m; i++) {        tempArr[i] = arr[(k + i) % n];    }Â
    // Sort the new array    sort(tempArr, tempArr + m);Â
    // Traverse the circular array and replace the     // corresponding elements with sorted elements    for (int i = 0; i < m; i++) {        arr[(k + i) % n] = tempArr[i];    }Â
    // If K + M is greater than N, traverse the remaining elements of the new array    // and replace the corresponding elements in the circular array arr[]    if (k + m > n) {        for (int i = m; i < n - k; i++) {            arr[(k + i) % n] = tempArr[i - m];        }    }}Â
Â
int main() {Â Â Â Â int arr[] = {4, 1, 6, 5, 3};Â Â Â Â int K = 2, M = 3;Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â
    sortCircularArray(arr, N, K, M);Â
    // Print the modified circular array    for (int i = 0; i < N; i++) {        cout << arr[i] << " ";    }    cout << endl;Â
    return 0;} |
Java
import java.util.Arrays;Â
public class Main {    public static void sortCircularArray(int[] arr, int n,                                         int k, int m)    {        // Create a new array of size M and copy the        // M elements starting from index K        int[] tempArr = new int[m];        for (int i = 0; i < m; i++) {            tempArr[i] = arr[(k + i) % n];        }Â
        // Sort the new array        Arrays.sort(tempArr);Â
        // Traverse the circular array and replace the        // corresponding elements with sorted elements        for (int i = 0; i < m; i++) {            arr[(k + i) % n] = tempArr[i];        }Â
        // If K + M is greater than N, traverse the        // remaining elements of the new array and replace        // the corresponding elements in the circular array        // arr[]        if (k + m > n) {            for (int i = m; i < n - k; i++) {                arr[(k + i) % n] = tempArr[i - m];            }        }    }Â
    public static void main(String[] args)    {        int[] arr = { 4, 1, 6, 5, 3 };        int K = 2, M = 3;        int N = arr.length;Â
        sortCircularArray(arr, N, K, M);Â
        // Print the modified circular array        for (int i = 0; i < N; i++) {            System.out.print(arr[i] + " ");        }    }} |
Python3
def sortCircularArray(arr, n, k, m):    # Create a new array of size M and copy the    # M elements starting from index K    tempArr = [0] * m    for i in range(m):        tempArr[i] = arr[(k + i) % n]Â
    # Sort the new array    tempArr.sort()Â
    # Traverse the circular array and replace the    # corresponding elements with sorted elements    for i in range(m):        arr[(k + i) % n] = tempArr[i]Â
    # If K + M is greater than N, traverse the remaining elements of the new array    # and replace the corresponding elements in the circular array arr[]    if k + m > n:        for i in range(m, n - k):            arr[(k + i) % n] = tempArr[i - m]Â
Â
if __name__ == '__main__':Â Â Â Â arr = [4, 1, 6, 5, 3]Â Â Â Â K = 2Â Â Â Â M = 3Â Â Â Â N = len(arr)Â
    sortCircularArray(arr, N, K, M)Â
    # Print the modified circular array    for i in range(N):        print(arr[i], end=" ") |
C#
using System;Â
public class GFG {    public static void SortCircularArray(int[] arr, int n,                                         int k, int m)    {        // Create a new array of size M and copy the        // M elements starting from index K        int[] tempArr = new int[m];        for (int i = 0; i < m; i++) {            tempArr[i] = arr[(k + i) % n];        }Â
        // Sort the new array        Array.Sort(tempArr);Â
        // Traverse the circular array and replace the        // corresponding elements with sorted elements        for (int i = 0; i < m; i++) {            arr[(k + i) % n] = tempArr[i];        }Â
        // If K + M is greater than N, traverse the        // remaining elements of the new array and replace        // the corresponding elements in the circular array        // arr[]        if (k + m > n) {            for (int i = m; i < n - k; i++) {                arr[(k + i) % n] = tempArr[i - m];            }        }    }Â
    public static void Main()    {        int[] arr = { 4, 1, 6, 5, 3 };        int K = 2, M = 3;        int N = arr.Length;Â
        SortCircularArray(arr, N, K, M);Â
        // Print the modified circular array        for (int i = 0; i < N; i++) {            Console.Write(arr[i] + " ");        }        Console.WriteLine();    }} |
Javascript
function sortCircularArray(arr, n, k, m) {    // Create a new array of size M and copy the     // M elements starting from index K    let tempArr = [];    for (let i = 0; i < m; i++) {        tempArr[i] = arr[(k + i) % n];    }Â
    // Sort the new array    tempArr.sort((a, b) => a - b);Â
    // Traverse the circular array and replace the     // corresponding elements with sorted elements    for (let i = 0; i < m; i++) {        arr[(k + i) % n] = tempArr[i];    }Â
    // If K + M is greater than N, traverse the remaining elements of the new array    // and replace the corresponding elements in the circular array arr[]    if (k + m > n) {        for (let i = m; i < n - k; i++) {            arr[(k + i) % n] = tempArr[i - m];        }    }}Â
// Main functionlet arr = [4, 1, 6, 5, 3];let K = 2, M = 3;let N = arr.length;Â
sortCircularArray(arr, N, K, M);Â
// Print the modified circular arrayfor (let i = 0; i < N; i++) {Â Â Â Â console.log(arr[i] + " ");} |
4 1 3 5 6
Time Complexity: O(M log M), where M is the number of elements to be sorted.
Auxiliary Space: O(M), since we are creating a new array of size M to store the M elements to be sorted.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] There you can find 18176 additional Information to that Topic: geeksforgeeks.org/sort-m-elements-of-given-circular-array-starting-from-index-k/ […]
… [Trackback]
[…] Find More on that Topic: geeksforgeeks.org/sort-m-elements-of-given-circular-array-starting-from-index-k/ […]
… [Trackback]
[…] Read More on on that Topic: geeksforgeeks.org/sort-m-elements-of-given-circular-array-starting-from-index-k/ […]
… [Trackback]
[…] Read More on that Topic: geeksforgeeks.org/sort-m-elements-of-given-circular-array-starting-from-index-k/ […]