本文介绍了如何检查是否数组已经排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此如何使这样的逻辑
so how to make such logic
int[] arr = {2, 5, 3};
if (/* arr is sorted */)
....
else
...
其糟糕的方法是的Array.sort无效
Its bad that method Array.sort is void
推荐答案
您不需要进行排序阵列,以检查它是否是排序。遍历每个连续的元素,并检查第一个小于第二;如果你发现一对而这是不正确的,该数组排序。
You don't need to sort your array to check if it's sorted. Loop over each consecutive pair of elements and check if the first is less than the second; if you find a pair for which this isn't true, the array is not sorted.
boolean sorted = true;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i+1]) {
sorted = false;
break;
}
}
这篇关于如何检查是否数组已经排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!