Sort a Rotated Sorted Array

You are given a rotated sorted array and your aim is to restore its original sort in place.

Expected to use O(1) extra space and O(n) time complexity.
Examples:

Input : [3, 4, 1, 2] 
Output : [1, 2, 3, 4]

Input : [2, 3, 4, 1]
Output : [1, 2, 3, 4]



We find the point of rotation. Then we rotate array using reversal algorithm.

 1. First find the split point where the sorting breaks.
 2. Then call the reverse function in three steps.
     - From zero index to split index.
     - From split index to end index.
     - From zero index to end index.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation for restoring original
// sort in rotated sorted array
#include <bits/stdc++.h>
using namespace std;
  
// Function to restore the Original Sort
void restoreSortedArray(int arr[], int n)
{
    for (int i = 0; i < n; i++) {
        if (arr[i] > arr[i + 1]) {
  
            // In reverse(), the first parameter
            // is iterator to beginning element
            // and second parameter is iterator
            // to last element plus one.   
            reverse(arr, arr+i+1);
            reverse(arr + i + 1, arr + n);
            reverse(arr, arr + n);
        }
    }
}
  
// Function to print the Array
void printArray(int arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
}
  
// Driver function
int main()
{
    int arr[] = { 3, 4, 5, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    restoreSortedArray(arr, n);
    printArray(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation for restoring original
// sort in rotated sorted array
class GFG 
{
  
// Function to restore the Original Sort
static void restoreSortedArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        if (arr[i] > arr[i + 1]) 
        {
  
            // In reverse(), the first parameter
            // is iterator to beginning element
            // and second parameter is iterator
            // to last element plus one. 
            reverse(arr,0,i);
            reverse(arr , i + 1, n);
            reverse(arr,0, n);
        }
    }
}
  
static void reverse(int[] arr, int i, int j) 
{
    int temp;
    while(i < j)
    {
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        i++;
        j--;
    }
}
  
// Function to print the Array
static void printArray(int arr[], int size)
{
    for (int i = 0; i < size; i++)
        System.out.print(arr[i] + " ");
}
  
// Driver code
public static void main(String[] args)
{
    int arr[] = { 3, 4, 5, 1, 2 };
    int n = arr.length;
    restoreSortedArray(arr, n - 1);
    printArray(arr, n);
}
}
  
// This code has been contributed by 29AjayKumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation for restoring original
// sort in rotated sorted array
using System;
      
class GFG 
{
  
// Function to restore the Original Sort
static void restoreSortedArray(int []arr, int n)
{
    for (int i = 0; i < n; i++)
    {
        if (arr[i] > arr[i + 1]) 
        {
  
            // In reverse(), the first parameter
            // is iterator to beginning element
            // and second parameter is iterator
            // to last element plus one. 
            reverse(arr,0,i);
            reverse(arr , i + 1, n);
            reverse(arr,0, n);
        }
    }
}
  
static void reverse(int[] arr, int i, int j) 
{
    int temp;
    while(i < j)
    {
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        i++;
        j--;
    }
}
  
// Function to print the Array
static void printArray(int []arr, int size)
{
    for (int i = 0; i < size; i++)
        Console.Write(arr[i] + " ");
}
  
// Driver code
public static void Main(String[] args)
{
    int[] arr = { 3, 4, 5, 1, 2 };
    int n = arr.Length;
    restoreSortedArray(arr, n - 1);
    printArray(arr, n);
}
}
  
// This code contributed by Rajput-Ji

chevron_right


Output:

1 2 3 4 5

We can binary search to find the rotation point as discussed here .

Efficient code approach using binary search:

  1. First find the index of minimum element (split index) in the array using binary search
  2. Then call the reverse function in three steps.
    • From zero index to split index.
    • From split index to end index.
    • From zero index to end index.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation for restoring original 
// sort in rotated sorted array using binary search 
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to find start index of array
int findStartIndexOfArray(int arr[], int low,int high)
{
    if (low>high)
    {
        return -1;
    }
  
    if (low == high)
    {
        return low;
    }
  
    int mid = low + (high-low)/2;
    if(arr[mid] > arr[mid+1])
        return mid+1;
  
    if(arr[mid-1] > arr[mid])
        return mid;
  
    if(arr[low] > arr[mid])
        return findStartIndexOfArray(arr, low, mid-1);
    else
        return findStartIndexOfArray(arr, mid+1, high);
}
  
// Function to restore the Original Sort
void restoreSortedArray(int arr[], int n)
{
    // array is already sorted
    if (arr[0] < arr[n-1])
        return;
      
    int start = findStartIndexOfArray(arr, 0, n-1);
    // In reverse(), the first parameter
    // is iterator to beginning element
    // and second parameter is iterator
    // to last element plus one.
    reverse(arr, arr + start);
    reverse(arr + start, arr + n);
    reverse(arr, arr + n);
      
}
  
// Function to print the Array
void printArray(int arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
}
  
// Driver function
int main()
{
    int arr[] = { 1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    restoreSortedArray(arr, n);
    printArray(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation for restoring original 
// sort in rotated sorted array using binary search 
import java.util.*;
  
class GFG
{
      
    // Function to find start index of array 
    static int findStartIndexOfArray(int arr[], 
                            int low, int high)
    {
        if (low > high) 
        {
            return -1;
        }
  
        if (low == high)
        {
            return low;
        }
  
        int mid = low + (high - low) / 2;
        if (arr[mid] > arr[mid + 1])
        {
            return mid + 1;
        }
  
        if (arr[mid - 1] > arr[mid]) 
        {
            return mid;
        }
  
        if (arr[low] > arr[mid])
        {
            return findStartIndexOfArray(arr, low, mid - 1);
        
        else
        {
            return findStartIndexOfArray(arr, mid + 1, high);
        }
    }
  
    // Function to restore the Original Sort 
    static void restoreSortedArray(int arr[], int n)
    {
        // array is already sorted 
        if (arr[0] < arr[n - 1]) 
        {
            return;
        }
  
        int start = findStartIndexOfArray(arr, 0, n - 1);
          
        // In reverse(), the first parameter 
        // is iterator to beginning element 
        // and second parameter is iterator 
        // to last element plus one. 
        Arrays.sort(arr, 0, start);
        Arrays.sort(arr, start, n);
        Arrays.sort(arr);
  
    }
  
    // Function to print the Array 
    static void printArray(int arr[], int size) 
    {
        for (int i = 0; i < size; i++) 
        {
            System.out.print(arr[i] + " ");
        }
    }
  
    // Driver code
    public static void main(String[] args) 
    {
        int arr[] = {1, 2, 3, 4, 5};
        int n = arr.length;
        restoreSortedArray(arr, n);
        printArray(arr, n);
    }
}
  
// This code contributed by Rajput-Ji

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation for restoring original 
// sort in rotated sorted array using binary search 
using System;
  
class GFG
{
      
    // Function to find start index of array 
    static int findStartIndexOfArray(int []arr, 
                            int low, int high)
    {
        if (low > high) 
        {
            return -1;
        }
  
        if (low == high)
        {
            return low;
        }
  
        int mid = low + (high - low) / 2;
        if (arr[mid] > arr[mid + 1])
        {
            return mid + 1;
        }
  
        if (arr[mid - 1] > arr[mid]) 
        {
            return mid;
        }
  
        if (arr[low] > arr[mid])
        {
            return findStartIndexOfArray(arr, low, mid - 1);
        
        else
        {
            return findStartIndexOfArray(arr, mid + 1, high);
        }
    }
  
    // Function to restore the Original Sort 
    static void restoreSortedArray(int []arr, int n)
    {
        // array is already sorted 
        if (arr[0] < arr[n - 1]) 
        {
            return;
        }
  
        int start = findStartIndexOfArray(arr, 0, n - 1);
          
        // In reverse(), the first parameter 
        // is iterator to beginning element 
        // and second parameter is iterator 
        // to last element plus one. 
        Array.Sort(arr, 0, start);
        Array.Sort(arr, start, n);
        Array.Sort(arr);
  
    }
  
    // Function to print the Array 
    static void printArray(int []arr, int size) 
    {
        for (int i = 0; i < size; i++) 
        {
            Console.Write(arr[i] + " ");
        }
    }
  
    // Driver code
    public static void Main() 
    {
        int []arr = {1, 2, 3, 4, 5};
        int n = arr.Length;
        restoreSortedArray(arr, n);
        printArray(arr, n);
    }
}
  
/* This code contributed by PrinciRaj1992 */

chevron_right


Output:

1 2 3 4 5

This article is contributed by Kshitiz Gupta.If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.