如何检查数组是否已经排序 [英] How to check if array is already sorted
本文介绍了如何检查数组是否已经排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
那么如何制作这样的逻辑
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;
}
}
这篇关于如何检查数组是否已经排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文