Domanda

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.

È stato utile?

Soluzione 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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top