簡體   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