user3371104
user3371104

Reputation: 269

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

Upvotes: 4

Views: 15668

Answers (11)

sayinmehmet47
sayinmehmet47

Reputation: 551

I have solved the algorithm in this way

function selectionSort(array) {
  let newArray=array
  let minValue=Math.min(...newArray)
  let index=0
  let indexMin=array.indexOf(minValue)
  while(newArray.length>1){
  let willChange=array[index]
  array[index]=minValue;
  index++;
  array[indexMin]=willChange;
  newArray=array.slice(index);
  minValue=Math.min(...newArray)
  indexMin=array.indexOf(minValue,index)
  }
return array
}


Upvotes: 0

Ibrahim Fariat
Ibrahim Fariat

Reputation: 1

This is a simple selection sort algorithm.

let array = [64, 25, 3, 3, 22, 11, 44, 43, 12, 65, 213, 7, 3, 6, 3, 0, 6565, 43];
const selectionSort = a => {
  let sa = [];
  let len = a.length;
 for(let i=0;i<len;i++) {
   sa.push(Math.min(...a));
    a.splice(a.indexOf(Math.min(...a)), 1)
 }
 return sa;
}
selectionSort(array) // returns sorted array;

Upvotes: 0

function selectionSort(inputArr) {
  let n = inputArr.length;

  for (let i = 0; i < n; i++) {
    // Finding the smallest number in the subarray
    let min = i;
    for (let j = i + 1; j < n; j++) {
      if (inputArr[j] < inputArr[min]) {
        min = j;
      }
    }
    if (min != i) {
      // Swapping the elements
      let tmp = inputArr[i];
      inputArr[i] = inputArr[min];
      inputArr[min] = tmp;
    }
  }
  return inputArr;
}

const numbers = [50, 30, 10, 40, 60];

console.log(selectionSort(numbers));

// Output: [ 10, 30, 40, 50, 60 ]

Upvotes: 0

mubasshir00
mubasshir00

Reputation: 349

function selectionSort(array_size, array) {
var min_index = 0;
for (var i = 0; i < array_size - 1; i++) {
    min_index = i;
    for (var j = i + 1; j < array_size; j++) {
        if (array[min_index] > array[j]) {
            min_index = j;
        }
    }
    [array[min_index],array[i]] = [array[i],array[min_index]]
}
return array

}

Upvotes: 0

Yuniel
Yuniel

Reputation: 1

const selectionSort = array => {
  const arr = Array.from(array); // avoid side effects
  for (let i = 0; i < arr.length - 1; i++) {
    let minPos = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[minPos]) {
        minPos = j;
      }
    }
    if (i !== minPos) {
      [arr[i], arr[minPos]] = [arr[minPos], arr[i]];
    }
  }
  return arr;
};

Upvotes: 1

Purkhalo Alex
Purkhalo Alex

Reputation: 3627

Eloquent solution:

const selectionSort = (items) => {
  items.forEach((val, i, arr) => {
    const smallest = Math.min(...arr.slice(i))
    const smallestIdx = arr.indexOf(smallest)

    if (arr[i] > arr[smallestIdx]) {
      const temp = arr[i]
      arr[i] = arr[smallestIdx]
      arr[smallestIdx] = temp
    }
  })

  return items
}

Standard solution:

const selectionSort = (arr) => {
  for (let i=0; i <= arr.length-1; i++) {
    // find the idnex of the smallest element
    let smallestIdx = i

    for (let j=i; j <= arr.length-1; j++) {
      if (arr[j] < arr[smallestIdx]) { 
        smallestIdx = j
      }
    }

    // if current iteration element isn't smallest swap it
    if (arr[i] > arr[smallestIdx]) {
      let temp = arr[i]
      arr[i] = arr[smallestIdx]
      arr[smallestIdx] = temp
    }
  }

  return arr
}

Testing:

console.log( // [14, 29, 56, 72, 92, 98] 
  selectionSort([29, 72, 98, 14, 92, 56]) 
)

Upvotes: 1

EugenSunic
EugenSunic

Reputation: 13703

The selection sort algorithm says: repeatedly find the minimum of the unsorted array.

Recursive approach

  1. Find the minimum number and its index/position
  2. Remove the min item from the array and append it at the end of the same one
  3. After each iteration, when finding the minimum provide the unsorted array (if not you will again get the previous minimum). See argument of Math.min

Note: the second argument of selectionSort (i) is needed in order to sort elements of the unsorted array

function selectionSort(arr, i) {
  if (i === 0) {
    return arr;
  }
  const min = Math.min(...arr.filter((x, j) => j < i));
  const index = arr.findIndex(x => x === min);
  arr.splice(index, 1);
  arr.push(min);
  return selectionSort(arr, --i);
}

const unsortedArr = [5, 34, 5, 1, 6, 7, 9, 2, 100];
console.log('result', selectionSort(unsortedArr , unsortedArr.length))

Upvotes: 0

Prashant Yadav
Prashant Yadav

Reputation: 81

You are basically doing the selection start is reverse order which will not work.

Your left should begin with 0 and right should end with arr.length.

newsort(arr, 0 ,arr.length); this should work.

Check out this link if you want to implement selection sort in javascript.

https://learnersbucket.com/examples/algorithms/selection-sort-in-javascript/

Upvotes: 0

shital
shital

Reputation: 1

function selectionSort(arr) {

    var temp = 0;
    for (var i = 0; i < arr.length; ++i) {
        for (var j = i + 1; j < arr.length; ++j) {
            if (arr[i] > arr[j]) { // compare element with the reset of other element
                temp = arr[i];  // swap the valuse from smallest to gretest
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return (arr);
}

selectionSort([4,6,5,3,7,9]);

Upvotes: -2

Clifford Fajardo
Clifford Fajardo

Reputation: 1447

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)

Upvotes: 5

user3504397
user3504397

Reputation: 61

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

Upvotes: 6

Related Questions