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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read