Update isSorted.md
This commit is contained in:
@ -3,17 +3,18 @@ title: isSorted
|
|||||||
tags: array,intermediate
|
tags: array,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Returns `1` if an array of numbers is sorted in ascending order, `-1` if it is sorted in descending order or `0` if it is not sorted.
|
Returns `1` if a numeric array is sorted in ascending order, `-1` if it is sorted in descending order or `0` if it is not sorted.
|
||||||
|
|
||||||
- Calculate the ordering `direction` for every pair of adjacent array elements.
|
- Calculate the ordering `direction` for the first pair of adjacent array elements.
|
||||||
- Return `0` if the `direction` changes or the `direction` sign if the last element is reached.
|
- Return `0` if the given array is empty, only has one element or the `direction` changes for any pair of adjacent array elements.
|
||||||
|
- Use `Math.sign()` to covert the final value of `direction` to `-1` or `1`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const isSorted = arr => {
|
const isSorted = arr => {
|
||||||
let direction = 0;
|
if (arr.length <= 1) return 0;
|
||||||
for (let i = 1; i < arr.length; i++) {
|
const direction = arr[1] - arr[0];
|
||||||
if (!direction) direction = arr[i] - arr[i - 1];
|
for (let i = 2; i < arr.length; i++) {
|
||||||
else if ((arr[i] - arr[i - 1]) * direction < 0) return 0;
|
if ((arr[i] - arr[i - 1]) * direction < 0) return 0;
|
||||||
}
|
}
|
||||||
return Math.sign(direction);
|
return Math.sign(direction);
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user