bubble sort array js code example

Example 1: javascript bubleshort example

// like using Array.reverse();
function bubbleReverse(arr) {
    for (let i = arr.length - 1; i > 0; i--) {
        for (let j = arr.length - 1; j > 0; j--) {
            if (arr[j] > arr[j - 1]) {
                let temp = arr[j];
                arr[j] = arr[j - 1];
                arr[j - 1] = temp;
            }
        }
    }
    return arr;
}

// like using Array.sort();
function bubbleSort(arr) {
    for (let i = 0; i < arr.length - 1; i++) {
        for (let j = 0; j < arr.length - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                let temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}

Example 2: buble sort in js

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