0

I'm trying to implement selection sort with javascript, but it seems that either i'm missing something or doing something absolutely wrong.
as you may understand from a first look, sortArray() seems to return arr with only one value 5 while it should return an array with as such [5,5,5,5,5,5].
worth mentioning is that when I comment line smallest_index = find_smallest(nums)
I get the supposed input; [5,5,5,5,5,5].

let nums = [2, 1, 3, 4, 5, 6];

function sortArray(nums) {
  let arr = new Array();
  let smallest_index;
  for (i = 0; i < nums.length; i++) {
    smallest_index = find_smallest(nums);
    arr.push("5");
  }

  return arr;
}

function find_smallest(arr) {
  let smallest = arr[0];
  let smallest_index = 0;

  for (i = 1; i < arr.length; i++) {
    if (arr[i] < smallest) {
      console.log("this");
      smallest = arr[i];
      smallest_index = i;
    }
  }
  return smallest_index;
}

console.log(sortArray(nums));

any help or thoughts as to what i may be not be realizing or doing ?

3
  • 2
    Make i a local variable in each function. find_smallest() is updating the variable i that's used in sortArray(), so the loop ends after the first iteration. Commented Jul 1, 2022 at 23:32
  • 1
    E.g. for (let i = 0; i < nums.length; i++) Commented Jul 1, 2022 at 23:32
  • @Barmar works! thanks for pointing that out, seems i had forgotten let exists for a reason :) Commented Jul 1, 2022 at 23:36

1 Answer 1

1

The problem is within your for loops. More specifically, you need to declare the variable i before using it. If you alter your code like the below snippet, then your code works just as expected:

let nums = [2, 1, 3, 4, 5, 6];

function sortArray(nums) {
  let arr = new Array();
  let smallest_index;
  for (let i = 0; i < nums.length; i++) {
    smallest_index = find_smallest(nums);
    arr.push("5");
  }

  return arr;
}

function find_smallest(arr) {
  let smallest = arr[0];
  let smallest_index = 0;

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < smallest) {
      console.log("this");
      smallest = arr[i];
      smallest_index = i;
    }
  }
  return smallest_index;
}

console.log(sortArray(nums));

The only difference is using

for (let i = 1; ...

instead of

for (i = 1; ...
Sign up to request clarification or add additional context in comments.

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.