Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

This is a Selection Sort exercise. After swapping the current value with the lower value after each pass, I want the code below to print:

Original array: [2,7,4,1,5,3]
1pass: [1,7,4,2,5,3]
2pass: [1,2,4,7,5,3]
3pass: [1,2,3,7,5,4]
4pass: [1,2,3,4,5,7]


JavaScript
var arr = [2,7,4,1,5,3];
for(var i=0; i<=arr.length-2; i++) {
  var imin = i;

  for(var j =i+1; j<=arr.length-1; j++) {
    if(arr[imin] > arr[j]) {
      imin = j;
    }
  }

  
  var temp = arr[i];
  arr[i] = arr[imin];
  arr[imin] = temp;

console.log(arr)// I would like for this array to show the swap at each pass
 
 
}


What I have tried:

I hadd created an empty array called store to put the swap values of the minimum value and the maximum value, but I still cant get my original array of 2,7,4,1,5,3 to print the following after each iteration

1pass: [1,7,4,2,5,3]
2pass: [1,2,4,7,5,3]
3pass: [1,2,3,7,5,4]
4pass: [1,2,3,4,5,7]

....
Posted
Updated 21-Nov-17 4:26am
v3
Comments
Iqra Ali 19-Nov-17 14:53pm    
Okay, and what did you expect to see and what was the problem? Your question is a bit unclear.
mappleleaf 21-Nov-17 10:27am    
Hello Iqra, I hope my question is clearer. thanks for the help

1 solution

OK, so create a function that iterates through the array and builds a string with the values in the format you want. Then just use console.log to output the string you built.

console.log isn't going to do that for you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900