簡體   English   中英

冒泡排序 Javascript

[英]Bubble Sort Javascript

我正在使用 javascript 在網頁中顯示氣泡排序方法中每次迭代結束時的數字列表。 該功能似乎無法排序,我無法弄清楚原因。

我假設我犯的錯誤是在循環區域周圍。

<!DOCTYPE html>
<html>
<head>
  <title>Bubble Sort</title>
<script type="text/javascript">


var array = new Array();
function pushArray(){
array.push((document.getElementById("elem").value));
    document.getElementById("elem").value = '';

}

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

var count = 1
function myFunction() {

    document.write("Array you entered was "+ array);
    var arrayLength = array.length;
    var i;
    var j;
    var k;
    for(i=0;i<arrayLength;i++)
    {
        for(j=i+1;j<arrayLength;j++)
        {
          if(array[i]<array[j])
          {
                    k=array[i];
                    array[i]=array[j];
                    array[j]=k;

          }
    document.write("<br/><br/>"+ count+"th iteration produced : " + array);
    count = count + 1;

        }


    }
    document.write("<br/><br/>After bubble sort in desending order " + array);
}

</script>
</head>
<body data-gr-c-s-loaded="true">

Enter the element here: <input type="text" id="elem" onkeypress="return isNumber(event)">
<br>
<button onclick="pushArray()">Add this element</button>

<p>Click the button to sort the array.</p>

<button onclick="myFunction()">Try it</button>

</body></html>

我發現了錯誤:

您正在獲取值並將其放置在數組中,從而創建一個只有一個元素的數組。 例如:數組[0] -> 132423434344 而不是數組[0] -> 1,數組[1] -> 3...

array.push((document.getElementById("elem").value));

使用下面的代碼

function pushArray(){
    array = document.getElementById("elem").value.split("");
    document.getElementById("elem").value = "";
}

我的冒泡排序功能:

function bubbleSort() {

document.write("Array you entered was " + array);

var arrayLength = array.length;
var i; var j; var temp; var count = 0;
for(i = 0; i < arrayLength; i++) {
    for(j = 0; j < arrayLength - 1; j++) {
        if(array[j] < array[j + 1]) {
            temp = array[j];
            array[j] = array[j + 1];
            array[j + 1] = temp;
        }
    }
}

document.write("<br/><br/>After bubble sort in desending order " + array);

}

function bubblesort () {

document.write("Array you entered was "+ array);
var arrayLength = array.length;
var i;
var j;
var k;
for (i=0; i < arrayLength; i++) {
for (j=0; j < arrayLength-1; j++) {
if (array[j] < array[j+1]) {
k = array[j];
array[j] = array[j+1];
array[j+1] = k;
}
}
}
document.write("<br/><br/>"+ count+"th iteration produced : " + array);
}

以下冒泡排序的時間復雜度在最佳情況下為 n,在最壞情況下為 n^2。

function bubbleSort(arr){

  console.log("Input Array");
  console.log(arr);

  let i = 0
  let temp;
  let notSorted;
  do {
    notSorted = false;
    for (let j = 0; j < arr.length-i; j++) {
      if (arr[j] > arr[j+1]) {
        notSorted = true;
        temp = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] = temp;
        console.log(arr[j],"swapped with",arr[j+1])
        console.log(arr);
      } else {
        console.log("SKIP");
      }
      console.log(j, arr.length-i);
    }
    i++;
  } while (notSorted)
  console.log("Sorted using Bubble Sort");
  return arr;
}
// console.log(bubbleSort([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])); // uncomment to run and see how efficient this algorithm is when array is sorted
console.log(bubbleSort([5,8,18,4,19,13,1,3,2,20,17,15,16,9,10,11,14,12,6,7]));

冒泡排序可以遞歸執行如下:

const recursiveBubbleSort = function (a, p = a.length-1) {
  if (p < 1) {
    return a;
  }
  for (let i = 0; i < p; i++) {
    if (a[i] > a[i+1]) {
      [a[i], a[i+1]] = [a[i+1], a[i]];
    }
  }
  return recursiveBubbleSort(a, p-1);
}

console.log(recursiveBubbleSort([2,1,4,7,3,9,5,6,8]));

使用 Javascript 的冒泡排序解決方案如下:

 bubbleSort = (array) => { let swaps = 0; let temp; for(let i=0 ; i <array.length;i++){ for(let j=0; j< array.length-1;j++){ if (array[j] > array[j + 1]) { temp = array[j+1]; array[j+1] = array[j]; array[j] = temp; swaps++; } } } console.log("Array is sorted in", swaps, "swaps."); console.log("First Element:", array[0]); console.log("Last Element:", array[array.length-1]); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM