今天我们来看看如果检查数组是否已排序。

实现思路:你可以取第一项和第二项,然后相减。如果第二项减去第一项为正,则对它们已经完成排序。依次为准,依次向前移动,使用索引并检查下两个索 引。

这里我们使用常规 for 循环,实现效果如下:

const sorted = arr => {
  let second_index
  for(let first_index = 0; first_index < arr.length; first_index++){
    second_index = first_index + 1
    if (arr[second_index] - arr[first_index] < 0) return false
  }
  return true
}

let arr1 = [1, 2, 3, 4, 5]
let arr2 = [1, 2, 4, 3, 5]
console.log(sorted(arr1)) // true
console.log(sorted(arr2)) // false