繁体   English   中英

冒泡排序不交换Javascript中的数组元素

[英]Bubble sort not swapping elements of array in Javascript

我正在创建一个简单的程序,该程序应该利用气泡排序算法对数字列表进行升序排序。

仅出于测试目的,我添加了行alert(unsortedNumbers); 如您所见,如果运行它,则无论算法通过多少次,数字都不会改变顺序。

该程序似乎陷入了无限循环,因为“另一遍”被重复打印到控制台。 按照此行的指示console.log("Another pass");

像冒泡排序算法一样,一旦它不必在某一遍上交换任何术语,我们就知道这是排序列表,我创建了swapped变量,但是看起来总是1 我认为这可能是由swapArrayElements()函数未交换条款引起的。

为什么函数不交换数组中术语的索引?

(代码在SO的代码段工具上似乎无法正常运行,可能必须复制到记事本文档中)

 function main(){ var unsortedNumbers =[7,8,13,1,6,9,43,80]; //Declares unsorted numbers array alert(unsortedNumbers); var swapped = 0; var len = unsortedNumbers.length; function swapArrayElements(index_a, index_b) { //swaps swapArrayElements[i] with swapArrayElements[ii] var temp = unsortedNumbers[index_a]; unsortedNumbers[index_a] = unsortedNumbers[index_b]; unsortedNumbers[index_b] = temp; } function finish(){ alert(unsortedNumbers); } function mainBody(){ for(var i =0;i<len;i++){ var ii =(i+1); if (unsortedNumbers[i]>unsortedNumbers[ii]){ console.log("Swap elements"); swapArrayElements(i,ii); swapped=1; // Variable 'swapped' used to check whether or not a swap has been made in each pass } if (ii = len){ if (swapped = 1){ // if a swap has been made, runs the main body again console.log("Another pass"); alert(unsortedNumbers); //Added for debugging swapped=0; mainBody(); }else{ console.log("Finish"); finish(); } } } } mainBody(); } 
 <head> </head> <body onload="main()"> </body> 

您的代码中有错误:

if (ii = len) {

并且

if (swapped = 1){ 

它应该是两倍等于

无效的条件检查会导致无限循环:

if (ii = len)if (swapped = 1)应该具有=====运算符。 这导致无限循环。

注意:根据最佳做法,您的代码不适合使用以避免全局变量的代码。 您不应使用全局变量并尝试传递变量并在处理后将其返回。

请参阅以避免全局变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM