forked from dscgecbsp/Hacktoberfest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.js
More file actions
23 lines (22 loc) · 760 Bytes
/
BubbleSort.js
File metadata and controls
23 lines (22 loc) · 760 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Bubble sort algorithm
*
* Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
*/
function bubbleSort(arr) {
let noSwaps = true
for (let index1 = arr.length; index1 > 0; index1--) {
for (let index2 = 0; index2 < index1 - 1; index2++) {
if (arr[index2] > arr[index2 + 1]) {
let temp = arr[index2 + 1]
arr[index2 + 1] = arr[index2]
arr[index2] = temp
noSwaps = false
}
}
if (noSwaps) break // if no swap is there then break (way to optimize)
}
return arr
}
// input your elements here
console.log(bubbleSort([2, 6, 7, 2, 3, 4, 10, 16, 11, 14]))