The shortest sub-array length to sort [algorithm]

Source: Internet
Author: User

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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.