Skip to content

Commit ebaf802

Browse files
committed
Add Bubble Sort
1 parent 69cec10 commit ebaf802

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

bubble-sort.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Algorithms: Implement Bubble Sort
3+
*
4+
* This is the first of several challenges on sorting algorithms. Given an array of unsorted items, we want to be able to return a sorted array. We will see several different methods to do this and learn some tradeoffs between these different approaches. While most modern languages have built-in sorting methods for operations like this, it is still important to understand some of the common basic approaches and learn how they can be implemented.
5+
*
6+
* Here we will see bubble sort. The bubble sort method starts at the beginning of an unsorted array and 'bubbles up' unsorted values towards the end, iterating through the array until it is completely sorted. It does this by comparing adjacent items and swapping them if they are out of order. The method continues looping through the array until no swaps occur at which point the array is sorted.
7+
*
8+
* This method requires multiple iterations through the array and for average and worst cases has quadratic time complexity. While simple, it is usually impractical in most situations.
9+
*
10+
* Instructions: Write a function bubbleSort which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
11+
*/
12+
13+
/**
14+
* Bubble Sort
15+
* @author Mike Mai
16+
* @param {Number[]} array
17+
* @return {Number[]}
18+
*
19+
* @example
20+
* bubbleSort([5,3,2,4,1]) //[1,2,3,4,5]
21+
*/
22+
function bubbleSort(array) {
23+
let swap = true;
24+
for (let i = 0, l = array.length; i < l-1 && swap; i++) {
25+
swap = false;
26+
27+
for (let j = 1; j < l-i; j++) {
28+
if (array[j] < array[j-1]) {
29+
const tmp = array[j];
30+
array[j] = array[j-1];
31+
array[j-1] = tmp;
32+
swap = true;
33+
}
34+
}
35+
36+
}
37+
38+
return array;
39+
}
40+
41+
console.log(bubbleSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]));

0 commit comments

Comments
 (0)