DEV Community

Manthan Bhatt
Manthan Bhatt

Posted on

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!

Top comments (1)

Collapse
 
muhammadtayyabbhutto profile image