How to use single-pass comparison In Javascript
To ascertain whether the array is monotonic, this method traverses the array once and compares each element with its neighbouring element. As it loops over the array, it updates the two flags it maintains—one for non-increasing and one for non-decreasing.
Example: Function to determine if an array is either entirely non-increasing or non-decreasing, providing a quick monotonicity check.
Javascript
function isMonotonic(array) { let isNonIncreasing = true ; let isNonDecreasing = true ; for (let i = 1; i < array.length; i++) { if (array[i] > array[i - 1]) { isNonIncreasing = false ; } if (array[i] < array[i - 1]) { isNonDecreasing = false ; } } return isNonIncreasing || isNonDecreasing; } console.log(isMonotonic([1, 2, 2, 4])); console.log(isMonotonic([3, 2, 5])); console.log(isMonotonic([1, 3, 9])); |
true false true
Check if Given Array is Monotonic in JavaScript
To determine whether an array is monotonic that is completely non-increasing or non-decreasing an array should have members ordered either ascending or descending in a direction-neutral fashion that is called monotone. A successful solution to this problem can simplify several algorithmic tasks.
In JavaScript, there are several ways to determine if an array is monotonic or not which are as follows:
Table of Content
- Using single-pass comparison
- Using sorting
- Using set comparison
- Using functional programming
- Using recursion
- Using Math(Sign Analysis):-