Syed Mehmood Ali
Syed Mehmood Ali

Reputation: 167

Check the sortedness Of An Array

I need an Algorithm which is used to find the N-element randomly-ordered integer array is either already sorted or not.

Upvotes: 1

Views: 633

Answers (2)

Stefan Kendall
Stefan Kendall

Reputation: 67802

Test if ascending:

for item i in items
    if i > nextitem
       return false

return true

Upvotes: 4

cletus
cletus

Reputation: 625037

Just loop through the array til you find an element that is less than the previous one. In C/Java'ish pseudo-code:

int prev = array[0];
boolean sorted = true;
for (int i=1; i<array.length; i++) {
  if (array[i] < prev) {
    sorted = false;
    break;
  }
  prev = array[i];
}

Upvotes: 7

Related Questions