0

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]));
1
  • You need to remember the index where cur came from. Then you should swap that index with a[i]. Commented Sep 26, 2023 at 4:54

2 Answers 2

1

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]));
Sign up to request clarification or add additional context in comments.

Comments

-1

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.