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

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

提交回复
热议问题