Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - Selection Sort in JavaScript

function newsort(arr, left, right){    

for(var i= left; i < right; ++i){
    var min = i;
    for (var j = i; j < right; ++j){
        if (arr[min] > arr[j]){
        min = j;
        }
    }

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

}
return arr;

}

var arr = [3,5,66,78,23,44,11,32,58];
alert(newsort(arr, arr.length, 0));

Above is the code for a function that I have written. I am still very new to JS, and as a result get confused at times when it comes to syntax. I currently just return the original array, but am trying to do the selection sort, the right/left/mid type.....I can't really tell what is going on at the moment. I am simply trying to sort and then return the array.

Anyone out there able to point me in the right direction?

thanks.....

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem with your code is that the left and right parameters are passed in the wrong way round. Here is the working code:alert(newsort(arr, 0 ,arr.length));


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...