18

so how to make such logic

int[] arr = {2, 5, 3};

if (/* arr is sorted */)
    ....
else 
    ...

Its bad that method Array.sort is void

6
  • 4
    What are you going to do if the array is not sorted? Commented Aug 7, 2013 at 18:40
  • You have to write your own logic. Iterate over the array, and test each element with the next element. Commented Aug 7, 2013 at 18:41
  • nothing, i just need somehow check if arr is sorted or not Commented Aug 7, 2013 at 18:43
  • 1
    How else would you check to see if the array were sorted? Commented Aug 7, 2013 at 18:47
  • 1
    Arrays.sort sorts the array. It doesn't check whether an array is sorted or not. Commented Aug 7, 2013 at 18:55

9 Answers 9

50

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;
    }
}
Sign up to request clarification or add additional context in comments.

13 Comments

It's impossible to be faster. You have to look at all the elements at least once, obviously. How else can you be share if you don't look at them all?
@OxomHuK You can put all of this in a function and just call that. Less code doesn't always mean better.
@Elist Why would you use that? You would lose the short-circuiting ability.
Whoever down voted was probably jealous. Great answer. Simple and efficient.
@Elist That only allows you to access one element of the array per iteration, we need to access two.
|
13
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;
}

5 Comments

+1 Use the generics... Very good toy, but, I believe, I have never needed to ask if an array is already sorted.
This is great, you come up with it on the fly or have it stashed away somewhere lol? I hope the latter for my fragile ego, good job. +1
Extracting length is really unnecessary, though, unless interpreting.
Note that this will not work with the OP's example, since he wants to check an array of primitives. In an ideal world, one would have an analogous method for each primitive array type.
@arshajii, Good point. I assumed that was a throwaway example, but to make it truly generic I'd have to use java.lang.reflect.Array along with @SuppressWarnings("unchecked") which would defeat all the generic safety checks you get from the compiler. I think overloading for primitive types is a good idea.
3

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

Comments

2
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;
}

1 Comment

should be arr.length, not arr.length()
1

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()

2 Comments

Very helpful answer, HOWEVER, wrong programming language. Java is not the same as javascript.
@JackGiffin, Java got stream right, you can use reduce() just fine
1

You can use .every

let isSorted = array.every((v, i) => (i === 0 || v <= array[i - 1]))
  || array.every((v, i) => (i === 0 || v >= array[i - 1]))

Comments

0
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.

Comments

0

A slight variation of the generics version by Mike Samuel but using Comparable<T> instead of Comparator<T>:

public static <T extends Comparable<? super T>> boolean isSorted(T[] elements) {
    int n = elements.length;
    for (int i = 1; i < n; ++i) {
        if (elements[i - 1].compareTo(elements[i]) > 0) {
            return false;
        }
    }
    return true;
}

Comments

0

Use .some() (or .every()) to return the result as soon as possible:

const isArraySortedAscending = (array) => array.length < 2 || !array.slice(1).some((v, i) => (v < array[i]))

const isArraySortedDescending = (array) => array.length < 2 || !array.slice(1).some((v, i) => (v > array[i]))

Test:

const isArraySortedAscending = (array) => array.length < 2 || !array.slice(1).some((v, i) => (v < array[i]))

const isArraySortedDescending = (array) => array.length < 2 || !array.slice(1).some((v, i) => (v > array[i]))

console.log(isArraySortedAscending([1, 2, 3])) // true
console.log(isArraySortedDescending([1, 2, 3])) // false

console.log(isArraySortedAscending([3, 2, 1])) // false
console.log(isArraySortedDescending([3, 2, 1])) // true

console.log(isArraySortedAscending([1, 3, 2])) // false
console.log(isArraySortedDescending([1, 3, 2])) // false

console.log(isArraySortedAscending([1])) // true
console.log(isArraySortedDescending([1])) // true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.