DEV Community

Manthan Bhatt
Manthan Bhatt

Posted on

5 2

Bubble Sort - Typescript

Bubble sort algorithm is simple and easy. In bubble sort every pair of adjacent value is compared and swap if the first value is greater than the second one. By this with every iteration the greatest value goes to the right side making it ascending order.

Bubble Sort

Time Complexity

  • Best: O(n)
  • Average: O(n^2)
  • Worst: O(n^2)

Code



const bubbleSort = (arr: number[]): number[] => {
    const len = arr.length;

    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len; j++) {
            if (arr[j] > arr[j + 1]) {
                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
            }
        }
    }

    return arr;
}

bubbleSort([5, 3, 1, 4, 6])


Enter fullscreen mode Exit fullscreen mode

Output



Output: [1, 3, 4, 5, 6]


Enter fullscreen mode Exit fullscreen mode

Here how the code is working

  • Iteration 0 (unsorted array): [5, 3, 1, 4, 6]
  • Iteration 1, key is 3 (was at index 1): [5, 3, 1, 4, 6] → [3, 5, 1, 4, 6]
  • Iteration 2, key is 1 (was at index 2): [3, 5, 1, 4, 6] → [1, 3, 5, 4, 6]
  • Iteration 3, key is 4 (was at index 3): [1, 3, 5, 4, 6] → [1, 3, 4, 5, 6]
  • Iteration 4, key is 6 (was at index 4): [1, 3, 4, 5, 6] → [1, 3, 4, 5, 6] — because 6 was already in the right place, no changes are made

That’s all for the bubble sort, thanks for reading!

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (2)

Collapse
 
hans_meier profile image
Hans Meier

your algorithm is wrong at let j it must be len-1, else you will get an undefinded error (in Java an IndexOutOfBoundException)

Collapse

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay