Sort an array where a subarray of a sorted array is in reverse order
Last Updated :
20 Feb, 2023
Given an array of N numbers where a subarray is sorted in descending order and rest of the numbers in the array are in ascending order. The task is to sort an array where a subarray of a sorted array is in reversed order.
Examples:
Input: 2 5 65 55 50 70 90
Output: 2 5 50 55 65 70 90
The subarray from 2nd index to 4th index is in reverse order.
So the subarray is reversed, and the sorted array is printed.
Input: 1 7 6 5 4 3 2 8
Output: 1 2 3 4 5 6 7 8
A naive approach will be to sort the array and print the array. Time Complexity of this approach will be O(N log n).
An efficient approach will be to find and store the starting index and ending index of the reversed subarray. Since the subarray is in descending order and the rest of the elements are in ascending order, only reversing the subarray will sort the complete array. Reverse the subarray using two pointer approach.
Below is the implementation of the above approach:
C++
// C++ program to sort an array where
// a subarray of a sorted array
// is in reversed order
#include <bits/stdc++.h>
using namespace std;
// Function to print the sorted array
// by reversing the subarray
void printSorted(int a[], int n)
{
int front = -1, back = -1;
// find the starting index of the
// reversed subarray
for (int i = 1; i < n; i++) {
if (a[i] < a[i - 1]) {
front = i - 1;
break;
}
}
// find the ending index of the
// reversed subarray
for (int i = n - 2; i >= 0; i--) {
if (a[i] > a[i + 1]) {
back = i + 1;
break;
}
}
// if no reversed subarray is present
if (front == -1 and back == -1) {
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return;
}
// swap the reversed subarray
while (front <= back) {
// swaps the front and back element
// using c++ STL
swap(a[front], a[back]);
// move the pointers one step
// ahead and one step back
front++;
back--;
}
for (int i = 0; i < n; i++)
cout << a[i] << " ";
}
// Driver Code
int main()
{
int a[] = { 1, 7, 6, 5, 4, 3, 2, 8 };
int n = sizeof(a) / sizeof(a[0]);
printSorted(a, n);
return 0;
}
Java
// Java program to sort an array where
// a subarray of a sorted array
// is in reversed order
import java.io.*;
class GFG
{
// Function to print the sorted array
// by reversing the subarray
static void printSorted(int a[], int n)
{
int front = -1, back = -1;
// find the starting index of the
// reversed subarray
for (int i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
front = i - 1;
break;
}
}
// find the ending index of the
// reversed subarray
for (int i = n - 2; i >= 0; i--)
{
if (a[i] > a[i + 1])
{
back = i + 1;
break;
}
}
// if no reversed subarray is present
if (front == -1 && back == -1)
{
for (int i = 0; i < n; i++)
System.out.println(a[i] + " ");
return;
}
// swap the reversed subarray
while (front <= back)
{
// swaps the front and back element
// using c++ STL
int temp = a[front];
a[front] = a[back];
a[back] = temp;
// move the pointers one step
// ahead and one step back
front++;
back--;
}
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
}
// Driver Code
public static void main (String[] args)
{
int a[] = { 1, 7, 6, 5, 4, 3, 2, 8 };
int n = a.length;
printSorted(a, n);;
}
}
// This code is contributed by anuj_67..
Python3
# Python 3 program to sort an array where
# a subarray of a sorted array is in
# reversed order
# Function to print the sorted array
# by reversing the subarray
def printSorted(a, n):
front = -1
back = -1
# find the starting index of the
# reversed subarray
for i in range(1, n, 1):
if (a[i] < a[i - 1]):
front = i - 1
break
# find the ending index of the
# reversed subarray
i = n - 2
while(i >= 0):
if (a[i] > a[i + 1]):
back = i + 1
break
i -= 1
# if no reversed subarray is present
if (front == -1 and back == -1):
for i in range(0, n, 1):
print(a[i], end = " ")
return
# swap the reversed subarray
while (front <= back):
# swaps the front and back element
# using c++ STL
temp = a[front]
a[front] = a[back]
a[back] = temp
# move the pointers one step
# ahead and one step back
front += 1
back -= 1
for i in range(0, n, 1):
print(a[i], end = " ")
# Driver Code
if __name__ == '__main__':
a = [1, 7, 6, 5, 4, 3, 2, 8]
n = len(a)
printSorted(a, n)
# This code is contributed by
# Sahil_Shelangia
C#
// C# program to sort an array where
// a subarray of a sorted array
// is in reversed order
using System;
class GFG
{
// Function to print the sorted array
// by reversing the subarray
static void printSorted(int []a, int n)
{
int front = -1, back = -1;
// find the starting index of the
// reversed subarray
for (int i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
front = i - 1;
break;
}
}
// find the ending index of the
// reversed subarray
for (int i = n - 2; i >= 0; i--)
{
if (a[i] > a[i + 1])
{
back = i + 1;
break;
}
}
// if no reversed subarray is present
if (front == -1 && back == -1)
{
for (int i = 0; i < n; i++)
{
Console.Write(a[i] + " ");
}
return;
}
// swap the reversed subarray
while (front <= back)
{
// swaps the front and back element
// using c++ STL
swap(a, front, back);
// move the pointers one step
// ahead and one step back
front++;
back--;
}
for (int i = 0; i < n; i++)
{
Console.Write(a[i] + " ");
}
}
static void swap(int[] a, int front,
int back)
{
int c = a[front];
a[front] = a[back];
a[back] = c;
}
// Driver Code
public static void Main()
{
int []a = {1, 7, 6, 5, 4, 3, 2, 8};
int n = a.Length;
printSorted(a, n);
}
}
// This code contributed by 29AjayKumar
PHP
<?php
// PHP program to sort an array where
// a subarray of a sorted array
// is in reversed order
// Function to print the sorted array
// by reversing the subarray
function printSorted($a, $n)
{
$front = -1; $back = -1;
// find the starting index of the
// reversed subarray
for ($i = 1; $i < $n; $i++)
{
if ($a[$i] < $a[$i - 1])
{
$front = $i - 1;
break;
}
}
// find the ending index of the
// reversed subarray
for ($i = $n - 2; $i >= 0; $i--)
{
if ($a[$i] > $a[$i + 1])
{
$back = $i + 1;
break;
}
}
// if no reversed subarray is present
if ($front == -1 && $back == -1)
{
for ($i = 0; $i < $n; $i++)
echo $a[$i] . " ";
return;
}
// swap the reversed subarray
while ($front <= $back)
{
// swaps the front and back element
// using c++ STL
$temp = $a[$front];
$a[$front] = $a[$back];
$a[$back] = $temp;
// move the pointers one step
// ahead and one step back
$front++;
$back--;
}
for ($i = 0; $i < $n; $i++)
echo $a[$i] . " ";
}
// Driver Code
$a = array(1, 7, 6, 5, 4, 3, 2, 8);
$n = sizeof($a);
printSorted($a, $n);
// This code is contributed
// by Akanksha Rai
JavaScript
<script>
// JavaScript program to sort an array where
// a subarray of a sorted array
// is in reversed order
// Function to print the sorted array
// by reversing the subarray
function printSorted(a , n) {
var front = -1, back = -1;
// find the starting index of the
// reversed subarray
for (i = 1; i < n; i++) {
if (a[i] < a[i - 1]) {
front = i - 1;
break;
}
}
// find the ending index of the
// reversed subarray
for (i = n - 2; i >= 0; i--) {
if (a[i] > a[i + 1]) {
back = i + 1;
break;
}
}
// if no reversed subarray is present
if (front == -1 && back == -1) {
for (i = 0; i < n; i++)
document.write(a[i] + " ");
return;
}
// swap the reversed subarray
while (front <= back) {
// swaps the front and back element
// using c++ STL
var temp = a[front];
a[front] = a[back];
a[back] = temp;
// move the pointers one step
// ahead and one step back
front++;
back--;
}
for (i = 0; i < n; i++)
document.write(a[i] + " ");
}
// Driver Code
var a = [ 1, 7, 6, 5, 4, 3, 2, 8 ];
var n = a.length;
printSorted(a, n);
// This code is contributed by todaysgaurav
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Similar Reads
C++ Program for Sorting array except elements in a subarray Given an array A positive integers, sort the array in ascending order such that element in given subarray (start and end indexes are input) in unsorted array stay unmoved and all other elements are sorted.Examples : Input : arr[] = {10, 4, 11, 7, 6, 20} l = 1, u = 3 Output : arr[] = {6, 4, 11, 7, 10
2 min read
Sort first k values in ascending order and remaining n-k values in descending order Given an array of size n, arrange the first k elements of the array in ascending order and the remaining n-k elements in descending order. Examples: Input: arr[] = {5, 4, 6, 2, 1, 3, 8, 9, -1}, k = 4 Output: 2 4 5 6 9 8 3 1 -1 Input: arr[] = {5, 4, 6}, k = 2 Output: 4 5 6 Algorithm: Store the first
11 min read
C++ Program to Check if it is possible to sort the array after rotating it Given an array of size N, the task is to determine whether its possible to sort the array or not by just one shuffle. In one shuffle, we can shift some contiguous elements from the end of the array and place it in the front of the array.For eg: A = {2, 3, 1, 2}, we can shift {1, 2} from the end of t
3 min read
C++ Program for Sorting all array elements except one Given an array, a positive integer, sort the array in ascending order such that the element at index K in the unsorted array stays unmoved and all other elements are sorted. Examples: Input : arr[] = {10, 4, 11, 7, 6, 20} k = 2; Output : arr[] = {4, 6, 11, 7, 10, 20} Input : arr[] = {30, 20, 10} k =
3 min read
C++ Program For Converting Array Into Zig-Zag Fashion Given an array of DISTINCT elements, rearrange the elements of array in zig-zag fashion in O(n) time. The converted array should be in form a c e . Example: Input: arr[] = {4, 3, 7, 8, 6, 2, 1} Output: arr[] = {3, 7, 4, 8, 2, 6, 1} Input: arr[] = {1, 4, 3, 2} Output: arr[] = {1, 4, 2, 3} Recommende
3 min read
Sort 2D array lexicographically Given a 2D array arr[] having N rows of variable size, the task is to sort the array in lexicographical order i.e., sort each row lexicographically and then sort those sorted rows. Examples: Input: arr[][] = { {23}, {59}, {23, 59} }Output: { {23}, {23, 59}, {59} }Explanation: The rows are sorted lex
6 min read
Check if reversing a sub array make the array sorted Given an array of n distinct integers. The task is to check whether reversing any one sub-array can make the array sorted or not. If the array is already sorted or can be made sorted by reversing any one subarray, print "Yes", else print "No". Examples: Input : arr [] = {1, 2, 5, 4, 3}Output : YesBy
15+ min read
Kth Smallest Element in a sorted array formed by reversing subarrays from a random index Given a sorted array arr[] of size N and an integer K, the task is to find Kth smallest element present in the array. The given array has been obtained by reversing subarrays {arr[0], arr[R]} and {arr[R + 1], arr[N - 1]} at some random index R. If the key is not present in the array, print -1. Examp
13 min read
Sort the Array by reversing the numbers in it Given an array arr[] of N non-negative integers, the task is to sort these integers according to their reverse. Examples: Input: arr[] = {12, 10, 102, 31, 15} Output: 10 31 12 15 102 Reversing the numbers: 12 -> 21 10 -> 01 102 -> 201 31 -> 13 15 -> 51 Sorting the reversed numbers: 01
6 min read
Length of smallest subarray to be removed such that the remaining array is sorted Given an array arr[] consisting of N integers, the task is to print the length of the smallest subarray to be removed from arr[] such that the remaining array is sorted. Examples: Input: arr[] = {1, 2, 3, 10, 4, 2, 3, 5}Output: 3Explanation:The smallest subarray to be remove is {10, 4, 2} of length
8 min read