Java 如何检查数组是否已经排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18111231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if array is already sorted
提问by OxomHuK
so how to make such logic
那么如何做出这样的逻辑
int[] arr = {2, 5, 3};
if (/* arr is sorted */)
....
else
...
Its bad that method Array.sort is void
Array.sort 方法无效,这很糟糕
回答by arshajii
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;
}
}
回答by Mike Samuel
public static <T>
boolean isArraySorted(T[] elements, Comparator<? super T> cmp) {
int n = elements.length;
for (int i = 1; i < n; ++i) {
if (cmp.compare(elements[i-1], elements[i]) > 0) { return false; }
}
return true;
}
回答by flavian
public static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (a[i + 1] < a[i]) {
return false;
};
}
return true;
}
回答by Anshul
Well you can check it in O(n) worst case linear time. A non-sorted array (assuming you mean sorting in ascending order) will have a trip point. That is at some point arr[i] > arr[i+1]
那么你可以在 O(n) 最坏情况的线性时间内检查它。未排序的数组(假设您的意思是按升序排序)将有一个跳闸点。那是在某个时候 arr[i] > arr[i+1]
All you need to do is
你需要做的就是
boolean is_array_sorted(int arr[]) {
for(int i=0; i < arr.len-1; i++) {
if(arr[i] > arr[i+1]) {
return false;
}
}
return true;
}
Just change the >
to <
if your array sort is supposed to be descending order
只要改变>
到<
,如果你的数组排序是应该降序
回答by user2276686
A shorter version:
一个较短的版本:
[0,1,2,3,4].reduce((a,v) => (a!==false) && (a <= v) ? v : false, -Infinity)
[4,3,1,2,0].reduce((a,v) => (a!==false) && (a >= v) ? v : false, +Infinity)
Be careful, as in some cases it isn't effective because it will loop through entire array without breaking prematurely.
请小心,因为在某些情况下它无效,因为它会遍历整个数组而不会过早中断。
回答by xhg
You can use .every
您可以使用 .every
let isSorted = array.every((v, i) => (i === 0 || v <= array[i - 1]))
|| array.every((v, i) => (i === 0 || v >= array[i - 1]))
回答by Nilanjan Banerjee
function isArraySorted(arr){
for(let i=0;i<arr.length;i++){
if(arr[i+1] && (arr[i+1] > arr[i])){
continue;
} else if(arr[i+1] && (arr[i+1] < arr[i])){
return false;
}
}
return true;
}
this worked for me.