Skip to content

Instantly share code, notes, and snippets.

@hanipcode
Created December 19, 2018 17:03
Show Gist options
  • Save hanipcode/560aade8e2b2daab51fa769d5a9bf36b to your computer and use it in GitHub Desktop.
Save hanipcode/560aade8e2b2daab51fa769d5a9bf36b to your computer and use it in GitHub Desktop.
// first we need to know is the array sorted
// the array can be sorted both ascending and descending
// can we check both at the same time ?
// first lets just check if they're sorted.
function isArraySorted(array) {
let isSortedDescending = true;
let isSortedAscending = true;
// descending
for (let i = 0; i < array.length; i = i + 1) {
if (i === 0) continue;
if (array[i] > array [i -1]) {
isSortedDescending = false;
}
}
// ascending
for (let i = 0; i < array.length; i = i + 1) {
if (i === 0) continue;
console.log(array[i]);
if (array [i] < array [ i - 1]) {
isSortedAscending = false;
}
}
return { isSortedDescending, isSortedAscending };
}
function isSortedAndHow(array) {
const { isSortedDescending, isSortedAscending } = isArraySorted(array);
if (!isSortedDescending && !isSortedAscending) return 'no';
if (isSortedDescending) return 'yes, descending';
return 'yes, ascending';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment