检查数组是否已排序,返回true或false

问题描述 投票:10回答:11

我正在编写一个简单的程序,如果一个数组被排序为false,则返回true,并且我在eclipse中不断得到一个异常,我只是想不通原因。我想知道是否有人可以看看我的代码并解释为什么我得到一个超出界限的数组异常。

public static boolean isSorted(int[] a) 
{
    int i;
    for(i = 0; i < a.length; i ++);{
        if (a[i] < a[i+1]) {
            return true;
        } else {
            return false;   
        }
    }
}
public static void main(String[] args)
{
    int ar[] = {3,5,6,7};
    System.out.println(isSorted(ar));   
}
java arrays sorting traversal
11个回答
32
投票

让我们看一下你构建的循环的更简洁版本:

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

我应该首先指出原始循环中的语法错误。也就是说,在大括号(;)之前有一个分号({),它开始循环体。应该删除该分号。另请注意,我重新格式化了代码的空白区域,使其更具可读性。

现在让我们讨论循环中发生的事情。循环迭代器i0开始,到a.length - 1结束。由于i作为数组的索引,因此有理由指出a[0]是第一个元素,而a[a.length - 1]是数组的最后一个元素。但是,在你的循环体中你也写了一个i + 1的索引。这意味着如果i等于a.length - 1,则索引等于a.length,它超出了数组的范围。

函数isSorted也存在相当大的问题,因为它第一次返回时为a[i] < a[i+1],而第一次返回时则为false;它实际上并没有检查数组是否完全排序!相反,它只检查前两个条目是否已排序。

具有类似逻辑但检查数组是否真正排序的函数是

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

0
投票
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;
}

-3
投票

Array.prototype.every

every()方法测试数组中的所有元素是否都通过了由提供的函数实现的测试。

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

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

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

3
投票

使用这个表达式,a[i+1],你正在运行数组的末尾。

如果必须与下一个元素进行比较,那么请尽早停止迭代1元素(并删除分号,Java将其解释为for循环体):

// stop one loop early ---v       v--- Remove semicolon here
for(i = 0; i < a.length - 1; i ++){

3
投票
int i;
for(i = 0; i < a.length - 1 && a[i] < a[i+1]; i++){}
return (i == a.length - 1);
  • 只访问数组元素,如果第一部分为假,则不处理结束条件的最后部分
  • 停在第一个未排序的元素上

3
投票

对于使用Java 8及更高版本的任何人来说,这是一个简单的单行程序:

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

或逻辑等效的替代方案:

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

2
投票

要检查数组是否已排序,我们可以比较数组中的相邻元素。

检查nulla.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;
}

2
投票

a[i+1]i == a.length会给你这个错误。

例如,在长度为10的数组中,您有元素0到9。

a[i+1]为9时,i将显示a[10],这是超出界限的。

修理:

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

此外,您的代码不会检查整个数组,只要调用return,检查循环就会终止。您只需检查第一个值,只检查第一个值。

并且,在你的for循环声明之后你有一个分号,这也导致了问题


0
投票

你不应该使用a[i+1],因为该值可能会也可能不会从阵列中消失。

例如:

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]

要解决这个问题,只需提前停止循环。

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

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

        return true;
    }else{
        return false;

    }

}

0
投票

降序数组也会排序。要考虑升序和降序数组,我使用以下内容:

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;
}

0
投票
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;
}

此函数检查阵列是否按升序排列。

© www.soinside.com 2019 - 2024. All rights reserved.