so how to make such logic
int[] arr = {2, 5, 3};
if (/* arr is sorted */)
....
else
...
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;
}
}
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]
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
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;
}
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.
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;
}
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.
Array.prototype.reduce()