Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created March 19, 2013 03:00
Show Gist options
  • Save charlespunk/5193402 to your computer and use it in GitHub Desktop.
Save charlespunk/5193402 to your computer and use it in GitHub Desktop.
Given a array of integers, write a method to find indices m and n such that if you sorted elements m through n, the entire array would be sorted. Minimize n-m (that is, find the smallest such sequence).
public static Result findUnsortedSequence(int[] input){
/* find the left sorted sequence */
int leftSortedSequenceEndIndex = findLeftSortedSequenceIndex(input);
if(leftSortedSequenceEndIndex == input.length - 1) reutn Result(-1, -1);
/* find the right sorted sequence */
int rightSortedSequenceBeginIndex = findRightSortedSequenceIndex(input);
/* find the biggest and samallest value in the middle */
int biggest = Integer.MIN_VALUE; int smallest = Integer.MAX_VALUE;
for(int i = leftSortedSequenceEndIndex; i <= rightSortedSequenceBeginIndex; i++){
if(input[i] > biggest) biggest = input[i];
if(input[i] < smallest) smallest = input[i];
}
/* slide left until less than smallest */
leftSortedSequenceEndIndex = shrinkLeft(leftSortedSequenceEndIndex, smallest, input);
/*slde right until bigger than biggest*/
rightSortedSequenceBeginIndex = shinkRight(rightSortedSequenceBeginIndex, biggest, input);
return Result(leftSortedSequenceEndIndex, rightSortedSequenceBeginIndex);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment