Bubble Sort (Sắp xếp nổi bọt)

1. Giới thiệu

2. Code

Normal Function

        function bubbleSort(arr) {
            let n = arr.length;
            for(let i = 0; i < n - 1; i++) {
                for(let j = 0; j < n - 1 - i; j++) {
                    if(arr[j] > arr[j + 1]) {
                        let temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
            return arr;
        }
        
        const arr = [64, 34, 25, 12, 22, 11, 90];
        console.log("Array: ", arr);
        
        const sortedArr = bubbleSort(arr);
        console.log("Array after sorted: ", sortedArr);

Output:

-----------

Arrow Function (Kể từ thuật toán này sẽ luôn sử dụng Arrow Function)

        const bubbleSort = (arr) => {
            let n = arr.length;
            for(let i = 0; i < n - 1; i++) {
                for(let j = 0; j < n - 1 - i; j++) {
                    if(arr[j] < arr[j + 1]) {
                        let temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
            return arr;
        }

        const arr = [46, 52, 27, 12, 21, 36, 96];
        console.log("Array: ", arr);
        
        const sortedArr = bubbleSort(arr);
        console.log("Array after sorted: ", sortedArr);

Output:

3. Kết Luận