문제

I want to make a method which checks if an array is sorted, with the smallest integer in the beginning of the array and the largest at the end. I named the array sequence.

public boolean isSorted(){
   int i = 1;
   while(i < sequence.length && sequence[i] >= sequence[i-1]){
      i++;
   }
   return i >= sequence.length;
}

I got to this code with the help of a friend, however I don't entirely understand it. What is returned as a boolean? As far as I could understand, reading on other posts, it will return true only when i >= sequence.length. Given the conditions by while, i will be bigger or the same as sequence.length only when the array is sorted.

Am I correct? Sorry if my formatting is terrible, I'm still new to stackoverflow.

도움이 되었습니까?

해결책 2

The loop seems to break as soon as a mismatch (a position in which proves that the array is not sorted as neighbours are sorted against the desired ordering) is found. If the loop does not break but terminate, the mismatch position points after the last character, which means that there is no mismatch.

다른 팁

Perhaps refactoring the method this way would make the code less complex and more readable:

public boolean isSorted(int[] sequence) {
    for (int idx = 1; idx < sequence.length; idx++) {
        if (sequence[idx] < sequence[idx-1]) return false;
    }
    return true;
 }

You are correct. The loop checks each pair of adjacent elements in the array. If each element is greater than the one before it, it must be sorted. If any pair does not fulfill the condition, the loop breaks immediately, leaving an i which is smaller than sequence.length, thus the condition i >= sequence.length tells you that the whole array was successfully processed and must be properly sorted.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top