bubble sort array javascript code example

Example 1: 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;
};

Example 2: boble sorting javascript

function bubbleSort(array) {
	for (let i = 0; i < array.length; i++) {
		for (let j = 0; j < array.length; j++) {
			let item = array[j];

			var nextItem = array[j + 1];
			if (item > nextItem) {
				array[j] = nextItem;
				array[j + 1] = item;
			}
		}
	}
	return array;
}

console.log(bubbleSort([9, 5, 7, 1, 0, 2, 4, 10, 1, 6, 3, 5, 8]));
console.log(bubbleSort([900, 5, 70, 0.1, 0, 02, 4, 100, 1, 6, 35, 56, 8]));

Example 3: bubble sort javascript

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)

Example 4: 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;
}