简体   繁体   English

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

[英]Check if an array is sorted, return true or false

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.我正在编写一个简单的程序,如果对数组进行排序则返回 true 否则返回 false 并且我在 eclipse 中不断收到异常,我只是想不通为什么。 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.我想知道是否有人可以看一下我的代码并解释一下为什么我会遇到数组越界异常。

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

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 .循环迭代器i0开始,以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.由于i用作数组的索引,因此指出a[0]是数组的第一个元素而a[a.length - 1]是数组的最后一个元素是有意义的。 However, in the body of your loop you have written an index of i + 1 as well.但是,在循环体中,您也编写了i + 1的索引。 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.这意味着如果i等于a.length - 1 ,则您的索引等于a.length ,它超出了数组的范围。

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;函数isSorted也有相当大的问题,因为它第一次返回真a[i] < a[i+1]而第一次不返回假; 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.
}

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

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

// 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仅访问数组元素,如果第一部分 ist false,则不处理结束条件的最后一部分
  • stops on first not sorted element在第一个未排序的元素上停止

a[i+1] when i == a.length will 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 i is 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.此外,您的代码不会检查整个数组,只要调用 return,检查循环就会终止。 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并且,您的 for 循环声明后有一个分号,这也会导致问题

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

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

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;

    }

}

If an array is not in ascending order or descending order then it's not sorted.如果一个数组不是按升序或降序排列的,那么它就不会被排序。

I will check whether neighbour elements are sorted or not.我将检查相邻元素是否已排序。 if any element is smaller than its previous element then It's not sorted in ascending order.如果任何元素小于其前一个元素,则它不按升序排序。

public static boolean isAscendingOrder(int[] a)
{  
    for ( int i = 0; i < a.length - 1 ; i++ ) {
        if ( a[i] > a[i+1] )
          return false;
    }
    return true;
}


// Same with Desending order
public static boolean isDescendingOrder(int[] a)
{  
    for ( int i = 0; i < a.length - 1 ; i++ ) {
        if ( a[i] < a[i+1] )
          return false;
    }
    return true;
}


public static boolean isSorted(int[] a)
{  
   return isAscendingOrder(a) || isDescendingOrder(a);
}

This function checks whether the array is in Sorted order or not irrespective of its order ie, ascending or descending.此函数检查数组是否按排序顺序排列,无论其顺序如何,即升序或降序。

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

If you want to check if the array is sorted DESC or ASC:如果要检查数组是按 DESC 还是 ASC 排序的:

boolean IsSorted(float [] temp)
{
    boolean result=true,result2=true;
    for (int i = 0; i < temp.length-1; i++)  
        if (temp[i]< temp[i + 1]) 
                result= false;

    for (int i = 0; i < temp.length-1; i++)  
        if (temp[i] > temp[i + 1])   
            result2= false;

    return result||result2;
}
bool checkSorted(int a[], int n) {
  for (int i = 1; i < n-1; i++) {
    if (a[i] > a[i-1]) {
      return false;
    }
  }
  return true;
}
public static boolean isSorted(int[] a) 
{
    int i,count=0;
    for(i = 0; i < a.length-1; i++);{
        if (a[i] < a[i+1]) {
            count=count+1;
        }  
        }
    if(count==a.length-1)
        return true;
    else
        return false;
}
public static void main(String[] args)
{
    int ar[] = {3,5,6,7};
    System.out.println(isSorted(ar));   
}

Here,this is code on checking the array is sorted or not, if it is sorted it return true, else false.I hope you understand the approach.在这里,这是检查数组是否排序的代码,如果已排序,则返回 true,否则返回 false。希望您理解该方法。

In the array, the index value is from 0 to n-1(n is the length of the array).在数组中,索引值是从0到n-1(n是数组的长度)。 When the loop comes at the last index ie n-1 the value of i+1 is n which is outside the array as the array index is only until n-1 so you are getting an array out of bound exception.当循环到达最后一个索引即 n-1 时,i+1 的值是 n,它在数组之外,因为数组索引仅直到 n-1,所以你得到一个数组越界异常。

The best way to test if an array is sorted or not is this way:测试数组是否排序的最佳方法是这样的:

boolean isSorted (int[] arr) {
        boolean isIt = true;
        int len = arr.length;
        for (int i = 0 ; i < arr.length ; i++ ) {
            len--;
            for (int j = i ; j < len; j++) {
                if (arr[i] < arr[j+1]) {isIt = true;}
                else {return false;}
            }
        }
        return true;
    }

Because if you use the following code you get true for this array which is not correct因为如果你使用下面的代码,你会得到这个数组的 true,这是不正确的

int[] test = {5,6,3,4}; int[] 测试 = {5,6,3,4};

for (i = 0; i < a.length; i++); { 
    if (a[i] < a[i + 1]) {
        return true;
    }
    else {
        return false;
    }
}
public class checksorted {
    boolean isSorted(int[] arr) {

        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                return false;
            }
        }
      return  true;
    }

Array.prototype.every Array.prototype.every

The every() method tests whether all elements in the array pass the test implemented by the provided function. every()方法测试数组中的所有元素是否通过提供的函数实现的测试。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM