Check if an array is descending, ascending or not sorted?

后端 未结 7 1628
不思量自难忘°
不思量自难忘° 2021-01-18 09:01

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 c

7条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-18 09:55

    "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 %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');
    }

提交回复
热议问题