|
| 1 | +/** |
| 2 | + * Sorts an array of numbers in ascending order using the Bubble Sort algorithm. |
| 3 | + * |
| 4 | + * This algorithm repeatedly steps through the list, compares adjacent elements, |
| 5 | + * and swaps them if they are in the wrong order. The pass through the list is |
| 6 | + * repeated until the array is sorted. |
| 7 | + * |
| 8 | + * This implementation runs in O(n²) time and O(1) space, making it simple but inefficient |
| 9 | + * for large datasets. |
| 10 | + * |
| 11 | + * @example |
| 12 | + * // Example 1: Sorting an unsorted array |
| 13 | + * // Input: [5, 1, 4, 2, 8] |
| 14 | + * // Output: [1, 2, 4, 5, 8] |
| 15 | + * const sorted = bubbleSort([5, 1, 4, 2, 8]); |
| 16 | + * // sorted === [1, 2, 4, 5, 8] |
| 17 | + * |
| 18 | + * @example |
| 19 | + * // Example 2: Sorting an already sorted array |
| 20 | + * // Input: [1, 2, 3, 4] |
| 21 | + * // Output: [1, 2, 3, 4] |
| 22 | + * const sorted = bubbleSort([1, 2, 3, 4]); |
| 23 | + * // sorted === [1, 2, 3, 4] |
| 24 | + * |
| 25 | + * @example |
| 26 | + * // Example 3: Sorting an array with duplicate values |
| 27 | + * // Input: [3, 2, 1, 2] |
| 28 | + * // Output: [1, 2, 2, 3] |
| 29 | + * const sorted = bubbleSort([3, 2, 1, 2]); |
| 30 | + * // sorted === [1, 2, 2, 3] |
| 31 | + * |
| 32 | + * @param arr - The array of numbers to sort. |
| 33 | + * @returns A new array containing the sorted elements in ascending order. |
| 34 | + */ |
| 35 | +export function bubbleSort(arr: number[]): number[] { |
| 36 | + if (arr.length <= 1) return arr; |
| 37 | + |
| 38 | + let size = arr.length; |
| 39 | + |
| 40 | + for (const _value in arr) { |
| 41 | + for (let i = 0; i <= size - 1; i++) { |
| 42 | + if (arr[i] > arr[i + 1]) { |
| 43 | + let a = arr[i + 1]; |
| 44 | + let b = arr[i]; |
| 45 | + |
| 46 | + arr.splice(i + 1, 1, b); |
| 47 | + arr.splice(i, 1, a); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return arr; |
| 53 | +} |
0 commit comments