Skip to content

Latest commit

 

History

History
55 lines (50 loc) · 1.17 KB

File metadata and controls

55 lines (50 loc) · 1.17 KB

Bubble Sort

function bubbleSort(arr) {
    for (let i = 0, n = arr.length - 1; i < n; i++) {
        if (arr[i] > arr[i + 1]) {
            [arr[i], arr[i+1]] = [arr[i+1], arr[i]];
            bubbleSort(arr);
        } else continue;
    }
    
    return arr;
}

bubbleSort([1, 6, 8, 3, -7, -4, 0, 5, 7, 3]);
// [-7, -4, 0, 1, 3, 3, 5, 6, 7, 8]

Mechanism

value comment
[1, 4, 2, 3] ok (1 <= 4)
[1, 4, 2, 3] wrong (4 not <= 2)
swap → [1, 2, 4, 3]
and repeat
[1, 2, 4, 3] ok (1 <= 2)
[1, 2, 4, 3] ok (2 <= 4)
[1, 2, 4, 3] wrong (4 not <= 3)
swap → [1, 2, 3, 4]
and repeat
[1, 2, 3, 4] ok (1 <= 2)
[1, 2, 3, 4] ok (2 <= 3)
[1, 2, 3, 4] ok (3 <= 4)