今天我們來看看如果檢查數(shù)組是否已排序。
實現(xiàn)思路:你可以取第一項和第二項螟炫,然后相減波附。如果第二項減去第一項為正,則對它們已經(jīng)完成排序。依次為準(zhǔn)掸屡,依次向前移動封寞,使用索引并檢查下兩個索 引。
這里我們使用常規(guī) for
循環(huán)仅财,實現(xiàn)效果如下:
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