Q:

bubble sort javascript

bubbleSort(Array) {
    let len = Array.length;
    for (let i = 0; i < len; i++) { //you can also use "for in", so you don't need the variable "len"
        for (let j = 0; j < len; j++) {
            if (Array[j] > Array[j + 1]) {
                let tmp = Array[j];
                Array[j] = Array[j + 1];
                Array[j + 1] = tmp;
            }
        }
    }
    return Array;
};
9
function bubblesort(array) {
    len = array.length;

    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len - i; j++) {
            let a = array[j];
            if (a != array[-1]) {
                var b = array[j + 1];
                if (a > b) {
                    array[j] = b;
                    array[j + 1] = a;
                }
            }
        }
    }
}

let array = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
bubblesort(array);
console.log(array)
2
function BubbleSort(arr) {
      const sortedArray = Array.from(arr);
      let swap;
      do {
        swap = false;
        for (let i = 1; i < sortedArray.length; ++i) {
          if (sortedArray[i - 1] > sortedArray[i]) {
            [sortedArray[i], sortedArray[i - 1]] = [sortedArray[i - 1], sortedArray[i]];
            swap = true;
          }
        }
      } while (swap)
      return sortedArray;
    }

    console.log(BubbleSort([7,99,1,88,34,2,90,7]));
1
let bubbleSort = (inputArr) => {    let 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;};
1
function bubbleSort(array) {
  const len = array.length;
  const retArray = array;
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len - i; j++) {
      const a = array[j];
      if (a !== array[-1]) {
        const b = array[j + 1];
        if (a > b) {
          retArray[j] = b;
          retArray[j + 1] = a;
        }
      }
    }
  }
  return retArray;
}
bubbleSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
0

New to Communities?

Join the community