Wave sort in Javascript

时间:2017-08-04 12:38:05

标签: javascript algorithm sorting

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;
}

3 个答案:

答案 0 :(得分:2)

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:

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;
}

var waved = waveSort([73, 80, 40, 86, 14, 96, 10, 56, 61, 84, 82, 36, 85]);
console.log(JSON.stringify(waved));

答案 1 :(得分:0)

function waveSort(arr){
    arr.sort((a,b)=>b-a);
    for(var i=1;i<arr.length;i+=2){
        var tmp = arr[i];
        arr[i]=arr[i+1];
        arr[i+1]=tmp;
    }
    return arr;
}
var wavesorted = waveSort([73, 80, 40, 86, 14, 96, 10, 56, 61, 84, 82, 36, 85]);
console.log(wavesorted);

答案 2 :(得分:0)

另一种方法是定义一个交换函数并在实际函数中调用它,例如:

const swap = (arr, i, j) => ([arr[i], arr[j]] = [arr[j], arr[i]]);

const waveSort = (arr) => {

  arr = arr.sort((a, b) => b - a);

for(let i = 1; i < arr.length; i += 2){
    if(arr[i-1] < arr[i]) {
      swap(arr, i-1, i)
}
if(i+1 < arr.length && arr[i+1]  < arr[i]) {
      swap(arr, i+1, i)
}
}
return arr;
}

var waved = waveSort([73, 80, 40, 86, 14, 96, 10, 56, 61, 84, 82, 36, 85]);
console.log(JSON.stringify(waved));

`