Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sethschori/98acb9a60c1358285deea93175d41ace to your computer and use it in GitHub Desktop.
Save sethschori/98acb9a60c1358285deea93175d41ace to your computer and use it in GitHub Desktop.
https://repl.it/C1TA/81 created by sethopia
/*
Check if Array is Sorted
Complete the function isSorted, which takes an array as inputed and outputs a boolean indicating if the array's contents are in ascending order.
isSorted([8,2,3,4])
// -> false
isSorted([2,3,4,8])
// -> true
*/
function isSorted(arr) {
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i+1]) return false;
}
return true;
}
console.log(isSorted([8,2,3,4]));
console.log(isSorted([2,3,4,8]));
/*
Below is the suggested answer. I wonder which is more efficient? Mine uses 6 lines of code, the suggested one uses 8.
The suggested one stringifies and also does a sort. Mine only does one loop, and if the array isn't sorted mine will
stop part-way through. So mine might be more efficient. However the biggest advantage that I see of the suggested
solution is that the code is more straight forward and clear to understand what's happening, whereas mine is a loop
that has a little more cognitive load to work through.
*/
//Helper function for sorting
function sortNums(a,b) {
return a - b;
}
function isSortedSuggested(arr) {
var original = arr.toString()
var sorted = arr.sort(sortNums).toString();
return original === sorted;
}
Native Browser JavaScript
>>> false
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment