Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.....

like image 400
user3371104 Avatar asked Dec 25 '22 11:12

user3371104


2 Answers

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

like image 196
user3504397 Avatar answered Dec 28 '22 05:12

user3504397


var selectionSort = function(array){
  for(var i = 0; i < array.length; i++){
    //set min to the current iteration of i
    var min = i;
    for(var j = i+1; j < array.length; j++){
      if(array[j] < array[min]){
       min = j;
      }
    }
    var temp = array[i];
    array[i] = array[min];
    array[min] = temp;
  }
  return array;
};
var array = [3,2,10,1]
console.log('selectionSort should return [1,2,3,10]-->',selectionSort(array));

It might be easier to reason with if you use a helper swap function:

//HELPER FUNCTION
var swap = function(array, firstIndex, secondIndex){
    var temp = array[firstIndex];
    array[firstIndex]  = array[secondIndex];
    array[secondIndex] = temp;
};
var array = [2,1];
swap(array, 0, 1)
console.log('swap should return [1,2] -->', array);


var selectionSort = function(array){
  for(var i = 0; i < array.length; i++){
    //set min to the current iteration of i
    var min = i;
    for(var j = i+1; j < array.length; j++){
      if(array[j] < array[min]){
        min = j;
      }
    }
    swap(array, i, min);
  }
  return array;
};
var array = [3,2,10,1]
console.log('selectionSort should return [1,2,3,10]-->',selectionSort(array));

Visual of selection sort:

[3,1,2]
 |-----> iterate over list. find that min = 1 so we swap current i (3) with min(1)

[1,3,2]
   |---> iterate over list. find that min = 2 so we swap current i (3) with min(2)

[1,2,3]
     |---> iterate over list. find that min = 3 so we swap current i (3) with min(3)
like image 45
Clifford Fajardo Avatar answered Dec 28 '22 06:12

Clifford Fajardo