如何打印完整迭代选择排序的每个交换 [英] How do I print each swap of a full iteration of selection sort

查看:88
本文介绍了如何打印完整迭代选择排序的每个交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



这是一个选择排序练习。在每次传递后用较低的值交换当前值后,我想要打印下面的代码:



原始数组:[2,7,4,1,5 ,3]

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

2 pass:[1,2,4,7,5,3] < br $>
3pass:[1,2,3,7,5,4]

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





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]


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
 
 
}





我尝试了什么:



我创建了一个名为store的空数组来放置交换值最小值和最大值,但我仍然无法得到我的原始阵列2,7,4,1,5,3在每次迭代后打印以下内容



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

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

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

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



....



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]

....

推荐答案

好的,所以创建一个迭代数组并使用所需格式的值构建字符串的函数。然后只需使用console.log输出你构建的字符串。



console.log不会为你做那个。
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.


这篇关于如何打印完整迭代选择排序的每个交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆