java怎么判断数组是否已经排序_java – 检查数组是否已排序,返回true或false

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

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

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

return true;

}

else {

return false;

}

}

我应该首先指出原始循环中的语法错误.也就是说,在大括号({)之前有一个分号(;),用于启动循环体.应删除该分号.

另请注意,我重新格式化了代码的空白区域,使其更具可读性.

现在让我们讨论循环中发生的事情.循环迭代器我从0开始并以a.length结束 – 1.因为我作为数组的索引起作用,所以指出a [0]是第一个元素和[a.length – 1]是有意义的数组的最后一个元素.但是,在循环体中,您还编写了索引i 1.这意味着如果i等于a.length – 1,则索引等于a.length,它超出了数组的范围.

函数isSorted也有相当大的问题,因为它在第一次返回时为真[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.

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值