I am writing an easy program the just returns true if an array is sorted else false and I keep getting an exception in eclipse and I just can\'t figure out why. I was wonder
You shouldn't use a[i+1]
because that value may or may not go off the array.
For example:
A = {1, 2, 3}
// A.length is 3.
for(i = 0; i < a.length; i ++) // A goes up to 3, so A[i+1] = A[4]
To fix this, simply stop the loop one early.
int i;
for(i = 0; i < a.length - 1; i ++);{
if (a[i] < a[i+1]) {
return true;
}else{
return false;
}
}
Array.prototype.every
The every() method tests whether all elements in the array pass the test implemented by the provided function.
arr.every(function (a, b) {
return a > b;
});
var arr = [1,2,3] // true
var arr = [3,2,1] // false
For anyone using Java 8 and above, here's a simple one-liner:
public static boolean isSorted(int[] array) {
return IntStream.range(0, array.length - 1).noneMatch(i -> array[i] > array[i + 1]);
}
Or a logically-equivalent alternative:
public static boolean isSorted(int[] array) {
return IntStream.range(0, array.length - 1).allMatch(i -> array[i] <= array[i + 1]);
}
bool checkSorted(int a[], int n) {
for (int i = 1; i < n-1; i++) {
if (a[i] > a[i-1]) {
return false;
}
}
return true;
}
public static boolean isSorted(int[] a)
{
for ( int i = 0; i < a.length - 1 ; i++ ) {
if ( a[i] > a[i+1] )
return false;
}
return true;
}
This function checks whether the array is in Ascending order or not.
boolean checkElements(int arr[], int first, int last) {
while(arr.length > first) {
if(arr[i] > arr[last-1]) {
if(arr[i] > arr[i+1])
return checkElements(arr, first+1, first+2);;
return false;
}else {
if(arr[i] < arr[i+1])
return checkElements(arr, first+1, first+2);
return false;
}
}
return true;
}