Check if an array is sorted, return true or false

落花浮王杯 提交于 2019-11-30 08:54:49

Let's look at a cleaner version of the loop you constructed:

for (i = 0; i < a.length; i++); { 
    if (a[i] < a[i + 1]) {
        return true;
    }
    else {
        return false;
    }
}

I should first point out the syntax error in the original loop. Namely, there is a semicolon (;) before the curly brace ({) that starts the body of the loop. That semicolon should be removed. Also note that I reformatted the white-space of the code to make it more readable.

Now let's discuss what happens inside your loop. The loop iterator i starts at 0 and ends at a.length - 1. Since i functions as an index of your array, it makes sense pointing out that a[0] is the first element and a[a.length - 1] the last element of your array. However, in the body of your loop you have written an index of i + 1 as well. This means that if i is equal to a.length - 1, your index is equal to a.length which is outside of the bounds of the array.

The function isSorted also has considerable problems as it returns true the first time a[i] < a[i+1] and false the first time it isn't; ergo it does not actually check if the array is sorted at all! Rather, it only checks if the first two entries are sorted.

A function with similar logic but which checks if the array really is sorted is

public static boolean isSorted(int[] a) {
// Our strategy will be to compare every element to its successor.
// The array is considered unsorted
// if a successor has a greater value than its predecessor.
// If we reach the end of the loop without finding that the array is unsorted,
// then it must be sorted instead.

// Note that we are always comparing an element to its successor.
// Because of this, we can end the loop after comparing 
// the second-last element to the last one.
// This means the loop iterator will end as an index of the second-last
// element of the array instead of the last one.
    for (int i = 0; i < a.length - 1; i++) {
        if (a[i] > a[i + 1]) {
            return false; // It is proven that the array is not sorted.
        }
    }

    return true; // If this part has been reached, the array must be sorted.
}

With this expression, a[i+1], you are running off the end of the array.

If you must compare to the next element, then stop your iteration 1 element early (and eliminate the semicolon, which Java would interpret as your for loop body):

// stop one loop early ---v       v--- Remove semicolon here
for(i = 0; i < a.length - 1; i ++){
int i;
for(i = 0; i < a.length - 1 && a[i] < a[i+1]; i++){}
return (i == a.length - 1);
  • only accesses array elements, last part of end condition are not processed if first part ist false
  • stops on first not sorted element

For anyone using Java 8 and above, here's a simple one-liner:

public static boolean isSorted(int[] array) {
    return IntStream.range(0, array.length - 1).noneMatch(i -> array[i] > array[i + 1]);
}

Or a logically-equivalent alternative:

public static boolean isSorted(int[] array) {
    return IntStream.range(0, array.length - 1).allMatch(i -> array[i] <= array[i + 1]);
}
savanibharat

To check whether array is sorted or not we can compare adjacent elements in array.

Check for boundary conditions of null & a.length == 0

public static boolean isSorted(int[] a){    

    if(a == null) {
        //Depends on what you have to return for null condition
        return false;
    }
    else if(a.length == 0) {
        return true;
    }
    //If we find any element which is greater then its next element we return false.
    for (int i = 0; i < a.length-1; i++) {
        if(a[i] > a[i+1]) {
            return false;
        }           
    }
    //If array is finished processing then return true as all elements passed the test.
    return true;
}
EyeOfTheHawks

a[i+1] when i == a.length will give you that error.

For example, in an array of length 10, you have elements 0 to 9.

a[i+1] when i is 9, will show a[10], which is out of bounds.

To fix:

for(i=0; i < a.length-1;i++)

Also, your code does not check through the whole array, as soon as return is called, the checking-loop is terminated. You are simply checking the first value, and only the first value.

AND, you have a semi-colon after your for loop declaration, which is also causing issues

You shouldn't use a[i+1] because that value may or may not go off the array.

For example:

A = {1, 2, 3}
// A.length is 3.
for(i = 0; i < a.length; i ++) // A goes up to 3, so A[i+1] = A[4]

To fix this, simply stop the loop one early.

int i;
for(i = 0; i < a.length - 1; i ++);{

    if (a[i] < a[i+1]) {

        return true;
    }else{
        return false;

    }

}

A descending array is also sorted. To account for both ascending and descending arrays, I use the following:

public static boolean isSorted(int[] a){
    boolean isSorted = true;
    boolean isAscending = a[1] > a[0];
    if(isAscending) {
        for (int i = 0; i < a.length-1; i++) {
            if(a[i] > a[i+1]) {
                isSorted = false;
                break;
            }           
        }
    } else {//descending
        for (int i = 0; i < a.length-1; i++) {
            if(a[i] < a[i+1]) {
                isSorted = false;
                break;
            }           
        }  
    }    
    return isSorted;
}
public static boolean isSorted(int[] a)
{  
    for ( int i = 0; i < a.length - 1 ; i++ ) {
        if ( a[i] > a[i+1] )
          return false;
    }
    return true;
}

This function checks whether the array is in Ascending order or not.

boolean checkElements(int arr[],  int first, int last) {
    while(arr.length > first) {
        if(arr[i] > arr[last-1]) {
            if(arr[i] > arr[i+1])
                return checkElements(arr, first+1, first+2);;
            return false;
        }else {
            if(arr[i] < arr[i+1])
                return checkElements(arr, first+1, first+2);
            return false;
        }
    }
    return true;
}

Array.prototype.every

The every() method tests whether all elements in the array pass the test implemented by the provided function.

arr.every(function (a, b) {
  return a > b;
});

var arr = [1,2,3] // true

var arr = [3,2,1] // false
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!