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

6
  • Classic case of staring at the screen too long by the looks of it, the function works - you are just passing the left and right parameters in the wrong order. Commented Apr 6, 2014 at 19:42
  • arrays have a sort method on them, [3,1,2].sort(), and use a custom sort function by passing it as an argument MDN sort doc Commented Apr 6, 2014 at 19:42
  • I do not understand what you are trying to do but if you want to sort the array why not using the sort() method? arr.sort(function(a,b){return a-b}) will sort the array. Check w3schools.com/jsref/jsref_sort.asp Commented Apr 6, 2014 at 19:44
  • 3
    @PatrickEvans it may be on educational purpose Commented Apr 6, 2014 at 19:46
  • @aduch, which is why I didn't say he should use it :). Since he said he was new to js was letting him know there was a way to sort and a way to make use of a custom sort method. Commented Apr 6, 2014 at 19:53

11 Answers 11

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

That is why IMO an appropriate name for left and right would be start and end.
5
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)

1 Comment

Destructuring, a feature that came to JavaScript in ES2015, makes it possible to handle the swap in one line: [array[i], array[min]] = [array[min], array[i]];. It's still good to know how to write your own swap function, but destructuring is a great new tool to have in your tool belt. You can read more about destructuring on MDN.
1

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

Comments

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

Comments

0

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/

Comments

0

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

Comments

0
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

}

Comments

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 ]

Comments

0

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;

Comments

0

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
}


Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.