-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathBubbleSort.js
More file actions
66 lines (56 loc) · 1.27 KB
/
BubbleSort.js
File metadata and controls
66 lines (56 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* Bubble Sort is an algorithm to sort an array. It
* compares adjacent elements and swaps their position.
* The big O on bubble sort in worst and best case is O(N^2).
*
* Wikipedia: https://en.wikipedia.org/wiki/Bubble_sort
*/
/**
* Using 2 for loops.
*/
export function bubbleSort(list) {
if (!Array.isArray(list)) {
throw new TypeError('Given input is not an array')
}
if (list.length === 0) {
return []
}
const items = [...list]
const length = items.length
let noSwaps
for (let i = length; i > 0; i--) {
noSwaps = true
for (let j = 0; j < i - 1; j++) {
if (items[j] > items[j + 1]) {
;[items[j], items[j + 1]] = [items[j + 1], items[j]]
noSwaps = false
}
}
if (noSwaps) {
break
}
}
return items
}
/**
* Using a while loop and a for loop.
*/
export function alternativeBubbleSort(list) {
if (!Array.isArray(list)) {
throw new TypeError('Given input is not an array')
}
if (list.length === 0) {
return []
}
const arr = [...list]
let swapped = true
while (swapped) {
swapped = false
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
;[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]]
swapped = true
}
}
}
return arr
}