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.
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:
1 2 3 4 5 6 7 8
Time Complexity: O(n)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sort all even numbers in ascending order and then sort all odd numbers in descending order
- Merge two sorted linked lists such that merged list is in reverse order
- Sort a nearly sorted (or K sorted) array
- Sort first k values in ascending order and remaining n-k values in descending order
- Search an element in a reverse sorted array
- Reverse a subarray of the given array to minimize the sum of elements at even position
- Reverse a subarray to maximize sum of even-indexed elements of given array
- Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array
- Program to copy the contents of one array into another in the reverse order
- Print words of a string in reverse order
- Print Fibonacci Series in reverse order
- Print Doubly Linked list in Reverse Order
- Program to print numbers from N to 1 in reverse order
- Reverse Level Order Traversal
- Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted
- Longest increasing subsequence which forms a subarray in the sorted representation of the array
- Length of smallest subarray to be removed such that the remaining array is sorted
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Minimize Steps required to obtain Sorted Order of an Array
- Print all repeating adjacent pairs in sorted order from an array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.