Error in implementing selection sort in JavaScript

58 Views Asked by At

This code is to implement selection sort in JavaScript. I tried with the array [3,2,1] but it return [1,1,1]; the array [4,5,1,2,7] return [1,1,1,2,7]. I don't know where I went wrong. Please help!

function selectionSort(a) {
  var temp;
  for (let i = 0; i < a.length - 1; i++) {
    cur = a[i];
    for (let j = i + 1; j < a.length; j++) {
      if (a[j] < cur) {
        cur = a[j];
      }
    }
    if (a[i] != cur) {
      temp = cur;
      cur = a[i];
      a[i] = temp;
    }
  }
  return a;
}
console.log(selectionSort([4,5,1,2,7]));
2

There are 2 best solutions below

0
Dhruv Patel On

The issue in your selection sort implementation is that you're not swapping the values correctly when you find a smaller element in the inner loop. To fix the issue, you need to swap the elements by storing the current minimum value in a temporary variable and then assigning it to the correct position in the array.

function selectionSort(a) {
  for (let i = 0; i < a.length - 1; i++) {
    let minIndex = i; // Assume the current index contains the minimum value

    for (let j = i + 1; j < a.length; j++) {
      if (a[j] < a[minIndex]) {
        minIndex = j; // Update the index of the minimum value
      }
    }

    // Swap the elements at minIndex and i
    if (minIndex !== i) {
      let temp = a[i];
      a[i] = a[minIndex];
      a[minIndex] = temp;
    }
  }

  return a;
}

console.log(selectionSort([4, 5, 1, 2, 7]));
1
bhavna parmar On

use sort function for sorting array function selectionSort(array) { array.sort( function(a,b) { return a-b } ); return array; }