11/* Bubble Sort is an algorithm to sort an array. It
2- * compares adjacent element and swaps their position
3- * The big O on bubble sort in worst and best case is O(N^2).
4- * Not efficient.
5- * Somehow if the array is sorted or nearly sorted then we can optimize bubble sort by adding a flag.
2+ * compares adjacent elements and swaps their position.
3+ * The big O on bubble sort in worst and best case is O(N^2).
64 *
7- * In bubble sort, we keep iterating while something was swapped in
8- * the previous inner-loop iteration. By swapped I mean, in the
9- * inner loop iteration, we check each number if the number proceeding
10- * it is greater than itself, if so we swap them.
11- *
12- * Wikipedia: https://en.wikipedia.org/wiki/Bubble_sort
13- * Animated Visual: https://www.toptal.com/developers/sorting-algorithms/bubble-sort
5+ * Wikipedia: https://en.wikipedia.org/wiki/Bubble_sort
146 */
157
168/**
179 * Using 2 for loops.
1810 */
19- export function bubbleSort ( items ) {
11+ export function bubbleSort ( list ) {
12+ if ( ! Array . isArray ( list ) ) {
13+ throw new TypeError ( 'Given input is not an array' )
14+ }
15+
16+ if ( list . length === 0 ) {
17+ return [ ]
18+ }
19+
20+ const items = [ ...list ]
2021 const length = items . length
2122 let noSwaps
2223
2324 for ( let i = length ; i > 0 ; i -- ) {
24- // flag for optimization
2525 noSwaps = true
26- // Number of passes
2726 for ( let j = 0 ; j < i - 1 ; j ++ ) {
28- // Compare the adjacent positions
2927 if ( items [ j ] > items [ j + 1 ] ) {
30- // Swap the numbers
3128 ; [ items [ j ] , items [ j + 1 ] ] = [ items [ j + 1 ] , items [ j ] ]
3229 noSwaps = false
3330 }
@@ -43,7 +40,16 @@ export function bubbleSort(items) {
4340/**
4441 * Using a while loop and a for loop.
4542 */
46- export function alternativeBubbleSort ( arr ) {
43+ export function alternativeBubbleSort ( list ) {
44+ if ( ! Array . isArray ( list ) ) {
45+ throw new TypeError ( 'Given input is not an array' )
46+ }
47+
48+ if ( list . length === 0 ) {
49+ return [ ]
50+ }
51+
52+ const arr = [ ...list ]
4753 let swapped = true
4854
4955 while ( swapped ) {
0 commit comments