簡體   English   中英

檢查數組是否已排序,返回 true 或 false

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

我正在編寫一個簡單的程序,如果對數組進行排序則返回 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));   
}

讓我們看一下您構建的循環的更簡潔版本:

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]而第一次不返回假; 因此,它實際上並不檢查數組是否已排序! 相反,它只檢查前兩個條目是否已排序。

具有類似邏輯但檢查數組是否確實已排序的函數是

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

對於使用 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]);
}

使用此表達式a[i+1] ,您將跑出數組的末尾。

如果您必須與下一個元素進行比較,請盡早停止迭代 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);
  • 僅訪問數組元素,如果第一部分 ist false,則不處理結束條件的最后一部分
  • 在第一個未排序的元素上停止

a[i+1]i == a.length會給你那個錯誤。

例如,在長度為 10 的數組中,您有 0 到 9 個元素。

a[i+1]i為 9 時,將顯示a[10] ,超出范圍。

修理:

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

此外,您的代碼不會檢查整個數組,只要調用 return,檢查循環就會終止。 您只是檢查第一個值,並且只檢查第一個值。

並且,您的 for 循環聲明后有一個分號,這也會導致問題

要檢查數組是否已排序,我們可以比較數組中的相鄰元素。

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

降序數組也被排序。 為了同時考慮升序和降序數組,我使用以下內容:

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

您不應該使用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;

    }

}

如果一個數組不是按升序或降序排列的,那么它就不會被排序。

我將檢查相鄰元素是否已排序。 如果任何元素小於其前一個元素,則它不按升序排序。

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

此函數檢查數組是否按排序順序排列,無論其順序如何,即升序或降序。

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

如果要檢查數組是按 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));   
}

在這里,這是檢查數組是否排序的代碼,如果已排序,則返回 true,否則返回 false。希望您理解該方法。

在數組中,索引值是從0到n-1(n是數組的長度)。 當循環到達最后一個索引即 n-1 時,i+1 的值是 n,它在數組之外,因為數組索引僅直到 n-1,所以你得到一個數組越界異常。

測試數組是否排序的最佳方法是這樣的:

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

因為如果你使用下面的代碼,你會得到這個數組的 true,這是不正確的

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

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