0

I was doing a little coding challenge, and it was to write a function that would return true if the arr parameter, which was an array of number, was sorted in ascending order. I can't seem to figure this out, but my code, no matter what, always returns true.

function inAscOrder(arr) {
  return arr.sort() === arr;
}
  • 8
    `sort` sorts the array *in-place* and returns the array itself, not a new array. So yes, this function will always return `true`. But even if it didn't sort the array in place, you cannot compare arrays like that. It will merely check whether the references are the same. See [How to compare arrays in JavaScript?](https://stackoverflow.com/q/7837456/218196) for how to compare arrays. – Felix Kling Jun 17 '18 at 03:38
  • What Felix said is all correct, but I'm guessing the objective of your exercise isn't to sort the array and check whether it is equivalent to the original. I would imagine the objective is to check whether the array is sorted by actually analyzing its contents. – JLRishe Jun 17 '18 at 03:43

3 Answers3

0

You do not need to sort the array to see if it is sorted. Just you need to check whether it is sorted or not.

static boolean arraySortedOrNot(int arr[], int n)
{

    // Array has one or no element
    if (n == 0 || n == 1)
        return true;

    for (int i = 1; i < n; i++)    
        // Unsorted pair found
        if (arr[i-1] > arr[i])
            return false;

    // No unsorted pair found
    return true;
}

reference link: https://www.geeksforgeeks.org/program-check-array-sorted-not-iterative-recursive/

A_sh
  • 21
  • 8
0

Since array is a mutable datatype, your arr will get modified when you call the sort method on it.

So arr.sort() will modify your array instead of just returning a sorted array. So thats why when u check again if its equal to arr, it will be the same sorted array.

To overcome this I suggest you copy the arr to some another array and sort that and test it.

peterh
  • 11,875
  • 18
  • 85
  • 108
Natesh bhat
  • 12,274
  • 10
  • 84
  • 125
0

As others have pointed out, a major issue with your version is that it uses the mutating sort. Although you could fix this by inserting a slice(0) or some such to clone the array, and then writing an index-by-index equality tester, it's much easier to simply test if each successive entry is larger than the previous one.

Perhaps the most elegant way to do that is through recursion. Here's one example:

const inAscOrder = (a) => a.length < 2 || (a[0] < a[1] && inAscOrder(a.slice(1)))

This might not be workable for larger arrays because of Javascript's recursion depth limits. But an iterative version of the same thing is fairly straightforward:

const inAscOrder = (a) => {
  if (a.length < 2) {return true}
  for (let i = 1; i < a.length; i++) {
    if (a[i -1] > a[i]) {return false}
  }
  return true
}
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103