Topic:
Given an unordered array, the length of the shortest sub-array that needs to be sorted is calculated.
For example: arr={1,5,3,4,2,6,7} returns 4 because only [5,3,4,2] needs to be sorted.
Ideas:
Solving this problem can be done with the time complexity O (N) and the additional spatial complexity of O (1).
Initialize variable nominindex=-1, right-to-left traversal, convenient procedure record the minimum value of the number that appears on the right, and remember it as Min. Assuming the current number is arr[i], if arr[i]>min, the Min value will inevitably move to the left of Arr[i] if it is to be ordered as a whole. Use Nominindex to record where this occurs on the leftmost side. If the traversal is complete, the value of Nominindex is still-1, indicating that the original array is always ordered from right to left, which returns 0 directly, i.e. it does not need to be sorted at all.
The next step is to traverse from left to right, and the traversing process records the maximum number of occurrences on the left. Remember as Max. Assuming the current number is arr[i], if Arr[i]<max, the value of Max will inevitably move to the right of arr[i] if sorted. Use the variable Momaxindex to record where this happens at the far right.
After traversing, Arr[nominindex...nomaxindex] is the part that really needs to be sorted. return it to its length.
Program:
Public Static intGetminlength (int[] arr) { if(arr = =NULL|| Arr.length < 2) { return0; } intMin = arr[arr.length-1]; intNominindex =-1; for(inti = arr.length-2; I! =-1; i--) { if(Arr[i] >min) {Nominindex=i; } Else{min=math.min (min, arr[i]); } } if(Nominindex = =-1) { return0; } intmax = Arr[0]; intNomaxindex =-1; for(inti = 1; I! = arr.length; i++) { if(Arr[i] <max) {Nomaxindex=i; } Else{Max=Math.max (Max, arr[i]); } } returnNomaxindex-nominindex + 1; }
The shortest sub-array length to sort [algorithm]