Class BubbleSort<T>

BubbleSort is a simple sorting algorithm that repeatedly steps through the array, compares adjacent elements and swaps them if they are in the wrong order. The pass through the array is repeated until the array is sorted.

The algorithm gets its name from the way smaller elements "bubble" to the top of the array. Although simple, it is not efficient for large datasets as it has a time complexity of O(n^2) in both the average and worst case scenarios.

The best-case time complexity is O(n) when the array is already sorted.

Example

const bubbleSort = new BubbleSort([3, 4, 1]);
bubbleSort.sort(); // returns new array with [1, 3, 4]
// or
BubbleSort.sort([3, 4, 1]); // returns new array with [1, 3, 4]

Example

const bubbleSort = new BubbleSort(
['alice', 'bob', 'charlie', 'alex', 'gavin'],
(a : string, b : string) => a.localeCompare(b)
);
bubbleSort.sort(); // returns new array with ['alex', 'alice', 'bob', 'charlie', 'gavin']

Type Parameters

  • T

Hierarchy

  • BubbleSort

Constructors

  • Type Parameters

    • T

    Parameters

    • array: T[] = []
    • comparatorFn: ((a, b) => number) = BubbleSort.defaultComparator
        • (a, b): number
        • Default comparator function used for sorting

          Parameters

          • a: any

            first element to compare

          • b: any

            second element to compare

          Returns number

          a negative number if a < b, 0 if a = b, a positive number if a > b

    Returns BubbleSort<T>

Properties

defaultComparator: ((a, b) => number)

Type declaration

    • (a, b): number
    • Parameters

      • a: T
      • b: T

      Returns number

size: number
values: T[]

Methods

  • Sorts the array using the BubbleSort algorithm.

    Returns T[]

    a new array with the elements sorted

    Example

    const bubbleSort = new BubbleSort([3, 4, 1]);
    bubbleSort.sort(); // returns new array with [1, 3, 4]
  • Default comparator function used for sorting

    Parameters

    • a: any

      first element to compare

    • b: any

      second element to compare

    Returns number

    a negative number if a < b, 0 if a = b, a positive number if a > b

  • Sorts the array using the BubbleSort algorithm. Static method, no need to instantiate class

    Parameters

    • array: any[]

      the array to be sorted

    • comparatorFn: ((a, b) => number) = ...

      the comparator function used for sorting, defaults to numerical comparison

        • (a, b): number
        • Default comparator function used for sorting

          Parameters

          • a: any

            first element to compare

          • b: any

            second element to compare

          Returns number

          a negative number if a < b, 0 if a = b, a positive number if a > b

    Returns any[]

    a new array with the elements sorted

Generated using TypeDoc