Javascript Array isSorted()

Description

Javascript Array isSorted()



/*/*  ww w .ja  v a  2s  .c o  m*/
 * check the array is sorted
 * return: if positive ->  1
 *         if negative -> -1
 *         not sorted  ->  0
 */
Array.prototype.isSorted = function() {
  return (function(direction) {
    return this.reduce(function(prev, next, i, arr) {
      if (direction === undefined)
        return (direction = prev <= next ? 1 : -1) || true;
      else
        return (direction + 1 ?
          (arr[i-1] <= next) : 
          (arr[i-1] >  next));
    }) ? Number(direction) : false;
  }).call(this);
}

Javascript Array isSorted()

Array.prototype.isSorted = function() {
  var input = this;

  for(var i = 0; i < input.length - 1; i++) {
    if(input[i] > input[i + 1]) {
      return false;
    }//from  w w  w.  java 2  s .  co m
  }

  return true;
}



PreviousNext

Related