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!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

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

Okay