简体   繁体   中英

Bubble Sort Javascript

I am using javascript to display in a web page the number list at the end of each iteration in the Bubble Sorting method. The function seems like failed to sort, and I couldn't figure it why.

I am assuming the mistake I made is around the loop area.

<!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>

I found the error:

You are taking the values and placing within the array, creating an array with only one element. ex: array[0] -> 132423434344 and not array[0] -> 1, array[1] -> 3...

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

Use the code below

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

My bubble sort function:

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);
}

The following Bubble Sort has time complexity of n in best case and n^2 in worst case.

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]));

Bubble Sort can be carried out recursively as follows:

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]));

Bubble Sort Solution With Javascript like this :

 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]); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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