冒泡排序Javascript

Bubble Sort Javascript

本文关键字:Javascript 冒泡排序      更新时间:2023-09-26

我使用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>

我发现了错误:

您正在获取值并将其放入数组中,创建一个只有一个元素的数组。例如:array[0] -> 132423434344 and not array[0] -> 1, array[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]);
  }