I have written a function to perform wave-sort as shown below. The resulting array should begin with a number bigger than the next one but my code is not doing that. For example if the input is:

[73, 80, 40, 86, 14, 96, 10, 56, 61, 84, 82, 36, 85]

…it gives an output of

[ 86, 96, 84, 85, 80, 82, 61, 73, 40, 56, 14, 36, 10 ]

instead of starting with a bigger number than the next, which is 96.

function waveSort(arr){ arr = arr.sort(function(a, b) { return b - a; }); for (var i = 1; i < arr.length; i += 2) { if (arr[i-1] > arr[i]) { var temp = arr[i]; arr[i] = arr[i-1]; arr[i-1] = temp; } if (i+1 < arr.length && arr[i+1] > arr[i]) { temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } } return arr; }

You have explicitly designed your function to start with a lower value.

In the first if you detect a situation where the first value is greater than the second, and if so, you swap them (when i = 1):

if (arr[i-1] > arr[i]) {

So it is normal you end up with a smaller value at index 0 than at index 1.

If you want your array to start with a “wave high”, then change the conditions in your two ifs: