简体   繁体   中英

Javascript: Bubble Sort

I have made a bubble sort algorithm (sorta) using JS. It works sometimes, but the problem is that it only iterates through the array once. Here is my code:

function bubble(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] > arr[i + 1]) {
      var a = arr[i]
      var b = arr[i + 1]
      arr[i] = b
      arr[i + 1] = a
    }
  }
  return arr;
}

Please look at the following sequence:

[5, 4, 3, 2, 1]

Now lets say you need to sort this in the ascending order using bubble sort.

So, you iterate the array and swap adjacent elements which are ordered otherwise.

Here is what you will get after the completion of the iteration

[4, 3, 2, 1, 5]

Now if you do this another time, you will get this:

[3, 2, 1, 4, 5]

Likewise, you need to repeat the iteration enough times to get it sorted fully. This means you need 2 nested loops. The inner loop is to iterate the array and the outer loop is to repeat the iteration.

Please see the step-by-step example of this article.

You need an inner loop to complete the sort correctly:

 function bubble(arr) { var len = arr.length; for (var i = 0; i < len ; i++) { for(var j = 0 ; j < len - i - 1; j++){ // this was missing if (arr[j] > arr[j + 1]) { // swap var temp = arr[j]; arr[j] = arr[j+1]; arr[j + 1] = temp; } } } return arr; } document.write(bubble([1,9,2,3,7,6,4,5,5]));

var array = [6,2,3,7,5,4,1];
function bubbleSort(arr) {
    for(let j=0;j<arr.length;j++) {
        for(let i = 0; i < arr.length; i++) {
            if(arr[i]>arr[i+1]) {
                var temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
            }
        }
    }      
    return arr;
}
console.log(bubbleSort(array));
const bubbleSort = (array)=>{
  let sorted = false;

  let counter =0;

  while(!sorted){
    sorted = true;  
    for(let i =0; i < array.length -1 -counter; i++){

      if(array[i] > array[i+1]){
        helper(i,i+1,array);        
        sorted = false;
      }
    } 
    counter++;
  }
  return array;

}

//swap function
function helper(i,j, array){
  return [array[i],array[j]] = [array[j],array[i]]
}

let array=[8,5,2,9,5,6,3];

console.log(bubbleSort(array))

My bubble sort with just a while loop :

function bubbleSort(arr){
  var sorted = false
  while (!sorted){
    sorted = true;
    arr.forEach(function (element, index, array){
      if (element > array[index+1]) {
        array[index] = array[index+1];
        array[index+1] = element;
        sorted = false;
      }
    });
  }
}
function bubble(arr) {//You need Two Loops for Bubble sort
  for (var i = 0; i < arr.length; i++) {//Outer Loop
   for(var j=0; j < arr.length - 1; j++){//Inner Loop
    if (arr[j] > arr[j + 1]) {
      var a = arr[j]
      var b = arr[j + 1]
      arr[j] = b
      arr[j + 1] = a
     }
   }
  }
  return arr;
}

Another form of bubble sort includes starting at the end of the array and placing the smallest element first and going till the largest. This is the code:

function bubbleSort(items) {  
    var length = items.length;
    for (var i = (length - 1); i >= 0; i--) {
        //Number of passes
        for (var j = (length - i); j > 0; j--) {
            //Compare the adjacent positions
            if (items[j] < items[j - 1]) {
                //Swap the numbers
                var tmp = items[j];
                items[j] = items[j - 1];
                items[j - 1] = tmp;
            }
        }
    }
}

Note Bubble sort is one of the slowest sorting algorithms.

It works for me. I commented the code for more understanding

 bubbleSort = (numbersArray) => { const arrayLenght = numbersArray.length; for (let i = 0; i < arrayLenght; i++) { for(let j = 0; j < arrayLenght; j++) { // Print only to debug // console.log(`i: ${i} - j: ${j}`); // console.log(`numbersArray[i]: ${numbersArray[i]} | numbersArray[j]: ${numbersArray[j]}`); // Check if current number is greater than the next number if (numbersArray[j] > numbersArray[j + 1]) { // Store current value to generate swap const currentNumber = numbersArray[j]; // Now the current position get value of the next position // And de next position get value of the current position numbersArray[j] = numbersArray[j + 1]; numbersArray[j + 1] = currentNumber; } } } // Debug: Print the sorted array console.log(`sorted array: ${numbersArray.toString()}`); } const numbers = [ [3, 10, 5, 7], [8, 5, 2, 9, 5, 6, 3], [4, 50, 28, 47, 9, 2097, 30, 41, 11, 3, 68], [3, 10, 5, 7, 8, 5, 2, 9, 5, 6, 3] ]; numbers.forEach(element => { bubbleSort(element); });

Output:

  • sorted array: 3,5,7,10
  • sorted array: 2,3,5,5,6,8,9
  • sorted array: 3,4,9,11,28,30,41,47,50,68,2097
  • sorted array: 2,3,3,5,5,5,6,7,8,9,10
package hasan;

public class hssd {

public static void main(String[] args) {


 int t=9;
int g=20;



 for (t=g;t>19;++t){

    System.out.println(7);
   int f=12;
   int r=15;

    for(r=f;r>5;++r)
        System.out.println(r+1000000000+"*"+1000000000);
    }
}

}
var arr = [5, 3, 4, 1, 2, 6];

function sort (arr) {
    for(let i=0; i < arr.length - 1; i++) {
        if(arr[i] > arr[i+1]) {
            let b = arr[i+1];

            arr[i+1] = arr[i];
            arr[i] = b;

            i = -1; // Resets the loop
        }
    }

    return arr;
}

console.log(sort(arr));

Try this (performance upgrade):

function bubbleSort(inputArr, reverse = false) {
    const len = inputArr.length;
    for (let i = 0; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
            let a = inputArr[i];
            let b = inputArr[j];
            if (reverse ? a < b : a > b) {
                const tmp = inputArr[j];
                inputArr[j] = inputArr[i];
                inputArr[i] = tmp;
            }
        }
    }
    return inputArr;
}

Use:

arr = [234,2,4,100, 1,12,5,23,12];
console.log(bubbleSort(arr)); // or console.log(bubbleSort(arr, true));

You need another loop:

var arr = [2, 1]
for(let i = 0;i<arr.length;i++){
    for(let b = 0; b<arr.length;i++){
        if(arr[b] > arr[b+1]){
            var first = arr[b]
            var second = arr[b + 1]
            arr[b] = second
            arr[b + 1] = first
        }
    }
}

Hope this helps I would recommend using quick sort if you want a high efficiency though.

Another bubble sort implementation:

const bubbleSort = array => {
  const arr = Array.from(array); // avoid side effects
  for (let i = 1; i < arr.length; i++) {
    for (let j = 0; j < arr.length - i; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  return arr;
};
const bubbleSort = (inputArr) => {
  const len = inputArr.length;

  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len; j++) {
      if (inputArr[j] > inputArr[j + 1]) {
        let tmp = inputArr[j];
        inputArr[j] = inputArr[j + 1];
        inputArr[j + 1] = tmp;
      }
    }
  }

  return inputArr;
};

const numbers = [50, 30, 10, 40, 60];

console.log(bubbleSort(numbers));

// Output: [ 10, 30, 40, 50, 60 ]
function bubbleSort(array) {
  var done = false;
  while (!done) {
   //alert(1)
    done = true;
    for (var i = 1; i < array.length; i += 1) {
      if (array[i - 1] > array[i]) {
      //alert(2)
       
        done = false;
        var tmp = array[i - 1];
        array[i - 1] = array[i];
        array[i] = tmp;
      }
    }
  }

  return array;
}

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