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

后端 未结 7 1626
不思量自难忘°
不思量自难忘° 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:38

    This is a question that requires some sort of loop, with several if statements because there are several cases you need to tackle:

    1. Array is empty or has only one element.
    2. All items in the array are equal
    3. Array is ascending - delta between 2 elements > 0, but some deltas may be 0
    4. Array is descending - delta between 2 elements < 0, but some deltas may be 0
    5. Not sorted - some deltas are > 0, and some are < 0

    Depending on how the sorted is defined in the question, cases 1 & 2 might be regarded as unsorted as well.

    function findSortOrder(arr) {
      if(arr.length < 2) { // case 1
        return 'not enough items'; // can also be 'unsorted'
      }
      
      var ascending = null;
      var nextArr = arr.slice(1); // create an array that starts from the 2nd element of the original array
    
      for(var i = 0; i < nextArr.length; i++) {
        if (nextArr[i] === arr[i]) { // neutral - do nothing
        } else if(ascending === null) { // define the the direction by the 1st delta encountered
          ascending = nextArr[i] > arr[i];
        } else if (ascending !== nextArr[i] > arr[i]) { // case 5
          return 'unsorted';
        }
      }
      
      if(ascending === null) { // case 2
        return 'all items are equal'; // can also be 'unsorted'
      }
      
      return ascending ? 'ascending' : 'descending'; // cases 3 & 4
    }
    
    console.log(findSortOrder([1])); // case 1
    
    console.log(findSortOrder([1, 1, 1, 1])); // case 2
    
    console.log(findSortOrder([1, 1, 2, 3, 7, 7])); // case 3
    
    console.log(findSortOrder([7, 2, 2, 1])); // case 4
    
    console.log(findSortOrder([7, 2, 1, 3, 2, 1])); // case 5

    0 讨论(0)
  • 2021-01-18 09:40
    function findOrder(array) {
        var asc = true;
        var desc = true;
        if(array.length < 2){
            return 'array is too small'
        }
        for(var i=1, len=array.length;i<len;i++){
            //if current element is bigger than previous array is not descending
            if(array[i]>array[i-1]){
                desc = false;
            //if current element is smaller than previous array is not ascending
            }else if(array[i]<array[i-1]){
                asc = false;
            }
    
            if(!asc && !desc){
                return 'not sorted'
            }
        }
    
        if(asc && desc){
            return 'array values are equal'
        }else if (asc){
            return 'array is ascending'
        }else {
            return 'array is descending'
        }
    }
    
    0 讨论(0)
  • 2021-01-18 09:42

    You could use a copy from the second element and check the predecessor for the wanted sort order.

    function checkArray(array) {
        var aa = array.slice(1);
        if (!aa.length) {
            return "Just one element";
        }
        if (aa.every((a, i) => array[i] > a)) {
            return "Ascending";
        }
        if (aa.every((a, i) => array[i] < a)) {
            return "Descending";
        }
        return "Unsorted";
    }
    
    console.log(checkArray([1, 2, 3, 4, 5]));
    console.log(checkArray([5, 4, 3, 2, 1]));
    console.log(checkArray([3, 1, 4, 2, 5]));
    console.log(checkArray([42]));

    0 讨论(0)
  • 2021-01-18 09:46

    Array.prototype.every passes its predicate an index, which you can use to get an element’s predecessor:

    function isAscending(arr) {
        return arr.every(function (x, i) {
            return i === 0 || x >= arr[i - 1];
        });
    }
    

    Here, we’re checking that every item (x) is greater than or equal to the item before it (arr[i - 1]) or has no item before it (i === 0).

    Flip >= to <= for isDescending.

    0 讨论(0)
  • 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<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');
    }

    0 讨论(0)
  • 2021-01-18 09:56

    Actually we may do even more by creating an Array method like natureOf which can tell us more about the nature of the array than just ascending, descendig or flat. Array.natureOf() shall give us a value between -1 and 1. If it is -1 the array is fully descending and 1 would mean fully ascending of course. Any value inbetween would give us the inclination of the array. As you would guess 0 would mean totally random or flat. (it's fairly easy to insert the logic to distinguish random from flat if that's also needed)

    Array.natureOf = function(a){
                       var nature = a.reduce((n,e,i,a) => i && a[i-1] !== e ? a[i-1] < e ? (n.asc++, n)
                                                                                         : (n.dsc++, n)
                                                                            : n, {asc:0, dsc:0});
                       return (nature.asc - nature.dsc) / (a.length-1);
                     };
    var arr = [1,2,3,4,5,6,7,8,9,10,7,11,13,14,15],
        brr = Array.from({length:2000000}, _ => ~~(Math.random()*1000000000));
    
    console.log(`The nature of "arr" array is ${Array.natureOf(arr)}`);
    console.log(`The nature of "brr" array is ${Array.natureOf(brr)}`);

    0 讨论(0)
提交回复
热议问题