简体   繁体   中英

Return Sorted Array Without Modifying Original Array

I'm having trouble with a function returning the original array as opposed to the sorted array. I tried to slice the array and return the sorted but it is not working. Any ideas on how to fix this?

function sortArr( comparator, array ){

var newArray = array.slice();

for(var i = 0; i < newArray.size; i++)
{
    var min = i;
    for(var x = i; x < newArray.size; x++)
    {
        if(comparator(newArray[min],newArray[x]) == true)
        {
            min = x;
        }
    }

    var temp = newArray[i];
    newArray[i] = newArray[min];
    newArray[min] = temp;

}

return newArray;

}

I fixed the function:

function sortArr( comparator, array ){
    /*your code here*/
    var i, x;
    var min;
    var newArray = array.slice();

    for(i = 0; i < newArray.length - 1; i++)
    {
        min = i;
        for(x = i + 1; x < newArray.length; x++)
        {
            if(comparator(newArray[min],newArray[x]) == true)
            {
                min = x;
            }
        }

        if(min != i){
            var temp = newArray[i];
            newArray[i] = newArray[min];
            newArray[min] = temp;
        }

    }

return newArray;

}

Copy the array with slice and then use native sort :

function sortArr(comparator, array) {
  return array.slice().sort(function(a,b) {
    return comparator(a,b) * 2 - 1;
  });
}

Your sorting algorithm doesn't look quite right. For a start the swapping of values should be inside the if statement. I would also advise to look at @Oriol's solution which is far more elegant.

function sortArr( comparator, array ){

var newArray = array.slice();

for(var i = 0; i < newArray.size; i++)
{
    var min = i;
    for(var x = i; x < newArray.size; x++)
    {
        if(comparator(newArray[min],newArray[x]) == true)
        {                   
            var temp = newArray[i];
            newArray[i] = newArray[min];
            newArray[min] = temp;
            min = x;
        }
    }
}

return newArray;

}
{"index.js":"var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  let newArr = globalArray.slice();\n  let  emptyArr = [];
  return emptyArr.concat(newArr).sort();
}
nonMutatingSort(globalArray);"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM