How to check if array is already sorted

后端 未结 7 1514
孤独总比滥情好
孤独总比滥情好 2020-12-03 21:39

so how to make such logic

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

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

Its bad that method Array.sort is void

相关标签:
7条回答
  • 2020-12-03 22:37

    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]))
    
    0 讨论(0)
提交回复
热议问题