Skip to content

Instantly share code, notes, and snippets.

@avanavana
Last active April 30, 2024 15:08
Show Gist options
  • Save avanavana/87c6fec2575c1fd01a1bb052b1d3685c to your computer and use it in GitHub Desktop.
Save avanavana/87c6fec2575c1fd01a1bb052b1d3685c to your computer and use it in GitHub Desktop.
[Algorithms] Bubble Sort - TypeScript Implementation
/**
* @file algorithm-bubbleSort.ts - A TypeScript implement of the bubbleSort algorithm
* @author Avana Vana
* @desc Algorithmic complexity:
* - Time complexity: Ω(n), Θ(n^2), O(n^2)
* - Space complexity: O(1)
*/
/**
* @function bubbleSort
* @desc Sorts an input array according to the Bubble Sort algorithm and returns the sorted array
* @template T
* @param {T[]} arr - input array of type T
* @returns {T[]} Sorted input array
*/
function bubbleSort<T>(arr: T[]): T[] {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) [ arr[j], arr[j + 1] ] = [ arr[j + 1], arr[j] ];
}
}
return arr;
}
bubbleSort([ 3, 7, 5, 2, 6, 1, 0, 4 ]);
// > [ 0, 1, 2, 3, 4, 5, 6, 7 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment