How to check if array is already sorted

后端 未结 7 1575
孤独总比滥情好
孤独总比滥情好 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:31

    A shorter version:

    [0,1,2,3,4].reduce((a,v) => (a!==false) && (a <= v) ? v : false, -Infinity)
    [4,3,1,2,0].reduce((a,v) => (a!==false) && (a >= v) ? v : false, +Infinity)
    

    Be careful, as in some cases it isn't effective because it will loop through entire array without breaking prematurely.

    Array.prototype.reduce()

提交回复
热议问题