In javascript (underscore) , how do I test whether a list of numbers is already sorted or not?
You can use _.every
to check whether all elements are in order:
_.every(arr, function(value, index, array) {
// either it is the first element, or otherwise this element should
// not be smaller than the previous element.
// spec requires string conversion
return index === 0 || String(array[index - 1]) <= String(value);
});
A simple solution would be to simply iterate over the list, examining whether each element is smaller than its next neighbor:
function is_sorted(arr) {
var len = arr.length - 1;
for(var i = 0; i < len; ++i) {
if(arr[i] > arr[i+1]) {
return false;
}
}
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With