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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19458278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:24:04  来源:igfitidea点击:

Check if an array is sorted, return true or false

javaarrayssortingtraversal

提问by user2101463

I am writing an easy program the just returns true if an array is sorted else false and I keep getting an exception in eclipse and I just can't figure out why. I was wondering if someone could take a look at my code and kind of explain why I'm getting an array out of bounds exception.

我正在编写一个简单的程序,如果数组按其他顺序排序,则返回 true,否则返回 false,并且我在 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));   
}

回答by Richard Tingle

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 istarts at 0and ends at a.length - 1. Since ifunctions 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 + 1as well. This means that if iis equal to a.length - 1, your index is equal to a.lengthwhich is outside of the bounds of the array.

现在让我们讨论一下循环内部发生了什么。循环迭代器i开始于0并结束于a.length - 1。由于i函数是数组的索引,因此指出它是数组a[0]的第一个元素和a[a.length - 1]最后一个元素是有道理的。然而,在你的循环体中你也写了一个索引i + 1。这意味着如果i等于a.length - 1,则您的索引等于a.length超出数组边界的那个。

The function isSortedalso 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.

该函数isSorted也有相当多的问题,因为它第一次返回真,第一次a[i] < a[i+1]不返回假;因此,它实际上根本不检查数组是否已排序!相反,它只检查前两个条目是否已排序。

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

回答by EyeOfTheHawks

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

a[i+1]什么时候i == a.length会给你那个错误。

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

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

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

a[i+1]i是 9 时,将显示a[10],这是越界的。

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.

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

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

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

回答by rgettman

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

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

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 forloop body):

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

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

回答by dtgee

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

您不应该使用,a[i+1]因为该值可能会或可能不会离开数组。

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;

    }

}

回答by 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

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

回答by Shogun

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
  • 只访问数组元素,如果第一部分为假,则不处理结束条件的最后一部分
  • 在第一个未排序的元素上停止

回答by iamwhitebox

Array.prototype.every

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

回答by Samil

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

回答by Bhuvanachandu

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.

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

回答by Jacob G.

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

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

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