检查数组按降序排序

检查数组按降序排序

本文介绍了检查数组按降序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写code,检查我的数组是按升序或降序排列。如果布尔上升是真的,那么我是否是升序。如果是假的,然后我检查递减。我需要帮助检查数组是否被降或不...我有code,检查这是写在下面上升:

 保护布尔isSorted(布尔升序){
    布尔结果= FALSE;

    如果(升序){
        的for(int i = 0; I< data.length-1;我++){
            如果(数据[1]  - ;数据[I + 1]){
                结果=真;
            }否则如果(数据[I]≥数据[I + 1]){
                结果= FALSE;
            }
        }
    } 其他 {
        // code检查降序
    }
}
 

解决方案

如果(以下简称升序支票)的第一部分是错误的,应该是:

 的for(int i = 0; I< data.length-1;我++){
    如果(数据[I]≥数据[I + 1]){
        返回false;
    }
}
返回true;
 

相反,降检查应(并注意这是足以改变比较运算符的方向):

 的for(int i = 0; I< data.length-1;我++){
    如果(数据[1]  - ;数据[I + 1]){
        返回false;
    }
}
返回true;
 

在这两种情况下,你必须尽快跳出循环为你找到一个的的数字对不抱上升有或降财产,只返回

I am writing code to check if my array is in ascending or descending order. If the boolean 'ascending' is true, then I check if it is ascending. If it is false, then I check for descending. I need help checking whether the array is descending or not... I have the code to check ascending which is written below:

protected boolean isSorted(boolean ascending) {
    boolean result = false;

    if (ascending) {
        for (int i=0;i<data.length-1;i++) {
            if(data[i] < data[i+1]) {
                result = true;
            } else if(data[i] > data[i+1]) {
                result = false;
            }
        }
    } else {
        //code to check for descending order
    }
}
解决方案

The first part of the if (the "ascending" check) is wrong, it should be:

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

Conversely, the descending check should be (and notice that it's enough to change the direction of the comparison operator):

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

In both cases, you have to break out of the loop as soon as you find a single pair of numbers that do not hold the ascending-or-descending property, and only return true after the loop exits.

这篇关于检查数组按降序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:26