Minimum length subarray of an unsorted array sorting which results in complete sorted array

preview_player
Показать описание
Given an unsorted array of integers, find the shortest subarray, which upon sorting will result in complete sorted array.

Algorithm:
1: From the beginning of the array, move to element in the array up to which the elements are sorted i.e. where array[i] is greater than array[i+1]. Set startIndex = i.
2: From the end of the array, move to the element up to which the elements are sorted in reverse order i.e. where array[j-1] is greater than array[j]. Set endIndex = j.
3: Find the minimum and maximum elements in the subarray from startIndex to endIndex.
4: Search the sorted array from 0 to startIndex to find the index at which minimum element will be in sorted array say, minIndex.
5: Search the sorted array from endIndex to end of array to find the index at which maximum element will be in sorted array say, maxIndex.
6: Resultant sub array is the subarray between minIndex to maxIndex.

Order of the Algorithm:
Time Complexity: O(n)
Space Complexity: O(1)

Code and Algorithm Visualization:

Рекомендации по теме
Комментарии
Автор

Dear Friends,

If you like our content and would like us to continue making great content for you, please spread the word about IDeserve.
A share/appreciation from you on social network would mean the world to us!


Thanks,
-Team IDeserve.

IDeserve
Автор

your channel is full of amazing content!!!

himanshuchhikara
Автор

Will your algorithm work if input is { 1, 4, 7, 3, 100, 48, 17, 26, 30, 45, 50, 62} --> I have kept your input as it is, only changed number 10 o 100

anilkumarsamal
Автор

Really cool stuff, highly recommended .

falakk
Автор

[2, 2, 2, 1, 1, 1] for this test case your algorithm may fails. please write a condition for this case

udaykiran
Автор

Thanks. This model is like insertion sort

shaikzuhair