I’m just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build. I got this question for homework but I can’t make it work for some reason, even though it seems “logic” to me. Check if an array is descending, ascending or not sorted using loops.
I’m just a noob so please try and help me figure this out as I only got to loops in my studies (: this is the code I wrote:
var array = [1, 2, 3, 7 ]; var d = 0; var c =0 ; var b = 1; var a = 0; for (var i = 1; i <= array.length; i++) { if (array[c]<array[b] && a!== -1 ){ d = -1; c =c+1; b = b+1; if(c==array.length){ console.log("asc"); break; }else{ continue; } } else if (array[c]>array[b] && d!==-1 ){ a = -1; d= d+1; b = b+1; if(i=array.length){ console.log("dsc"); break; }else{continue;} } else{ console.log("unsorted array"); break; } }
Advertisement
Answer
“Check if an array is descending, ascending or not sorted using loops”
// define the array var array = [1,2,3,7]; // keep track of things var isDescending = true; var isAscending = true; // we're looking ahead; loop from the first element to one before the last element for (var i=0, l=array.length-1; i<l; i++) { //////////////////////////////////////////////////////////// // log to the console to show what's happening for each loop iteration // this is the ith iteration console.log("loop iteration %s", i); // breaking isDescending down: // is this value greater than the next value? console.log("A: (%s > %s) = %s", array[i], array[i+1], (array[i] > array[i+1])); // have all values been descending so far? console.log("B: isDescending: %s", isDescending); // if this value is greater than the next and all values have been descending so far, isDescending remains true. Otherwise, it's set to false. console.log("are A and B both true? %s", (isDescending && (array[i] > array[i+1]))); // add a line break for clarity console.log(""); //////////////////////////////////////////////////////////// // true if this is greater than the next and all other so far have been true isDescending = isDescending && (array[i] > array[i+1]); // true if this is less than the next and all others so far have been true isAscending = isAscending && (array[i] < array[i+1]); } if (isAscending) { console.log('Ascending'); } else if (isDescending) { console.log('Descending'); } else { console.log('Not Sorted'); }