Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted.
1) If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between the indexes 3 and 8.
2) If the input array is [0, 1, 15, 25, 6, 7, 30, 40, 50], your program should be able to find that the subarray lies between the indexes 2 and 5.
1) Find the candidate unsorted subarray
a) Scan from left to right and find the first element which is greater than the next element. Let s be the index of such an element. In the above example 1, s is 3 (index of 30).
b) Scan from right to left and find the first element (first in right to left order) which is smaller than the next element (next in right to left order). Let e be the index of such an element. In the above example 1, e is 7 (index of 31).
2) Check whether sorting the candidate unsorted subarray makes the complete array sorted or not. If not, then include more elements in the subarray.
a) Find the minimum and maximum values in arr[s..e]. Let minimum and maximum values be min and max. min and max for [30, 25, 40, 32, 31] are 25 and 40 respectively.
b) Find the first element (if there is any) in arr[0..s-1] which is greater than min, change s to index of this element. There is no such element in above example 1.
c) Find the last element (if there is any) in arr[e+1..n-1] which is smaller than max, change e to index of this element. In the above example 1, e is changed to 8 (index of 35)
3) Print s and e.
The unsorted subarray which makes the given array sorted lies between the indees 3 and 8
Time Complexity: O(n)
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.
- Which sorting algorithm makes minimum number of memory writes?
- Find index of first occurrence when an unsorted array is sorted
- Find the minimum element in a sorted and rotated array
- Sorting array except elements in a subarray
- Why is it faster to process sorted array than an unsorted array ?
- Find the element whose multiplication with -1 makes array sum 0
- Sort an array where a subarray of a sorted array is in reverse order
- Find the length of largest subarray with 0 sum
- Find maximum average subarray of k length
- Search an element in an unsorted array using minimum number of comparisons
- Merging and Sorting Two Unsorted Stacks
- Find floor and ceil in an unsorted array
- Find the two numbers with odd occurrences in an unsorted array
- Find maximum (or minimum) sum of a subarray of size k
- Find start and ending index of an element in an unsorted array