Skip to content

Commit 8cf2823

Browse files
authored
Merge pull request #42 from khairalanam/khair
Add Bubble Sort Problem
2 parents f9c7560 + 2bf811b commit 8cf2823

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

L-I/0008 BubbleSort/BubbleSort.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const BubbleSort = (arr) => {
2+
for (let i = 0; i < arr.length - 1; i++) {
3+
for (let j = 0; j < arr.length - i - 1; j++) {
4+
if (arr[j] > arr[j + 1]) {
5+
temp = arr[j];
6+
arr[j] = arr[j + 1];
7+
arr[j + 1] = temp;
8+
}
9+
}
10+
}
11+
};
12+
13+
arr = [0, 4, 2, 3, 7, 3, 6, 2, 9, 10, 2, 6];
14+
arrOne = [45, 32, 12, 67, 86, 92, 29, 24, 53, 1, 6, 32, 56];
15+
16+
BubbleSort(arr);
17+
BubbleSort(arrOne);
18+
19+
console.log(arr);
20+
console.log(arrOne);

L-I/0008 BubbleSort/README.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# 0008 BubbleSort ( L-I )
2+
3+
## Problem
4+
5+
Implement a function that sorts an array in increasing order using bubble sort.
6+
7+
## Testcases
8+
9+
- Input: `[0, 4, 2, 3, 7, 3, 6, 2, 9, 10, 2, 6]` <br>
10+
Output: `[0, 2, 2, 2, 3, 3, 4, 6, 6, 7, 9, 10]`
11+
12+
- Input: `[45, 32, 12, 67, 86, 92, 29, 24, 53, 1, 6, 32, 56]` <br>
13+
Output: `[1, 6, 12, 24, 29, 32, 32, 45, 53, 56, 67, 86, 92]`
14+
15+
## Solution
16+
17+
```javascript
18+
const BubbleSort = (arr) => {
19+
for (let i = 0; i < arr.length - 1; i++) {
20+
for (let j = 0; j < arr.length - i - 1; j++) {
21+
if (arr[j] > arr[j + 1]) {
22+
temp = arr[j];
23+
arr[j] = arr[j + 1];
24+
arr[j + 1] = temp;
25+
}
26+
}
27+
}
28+
};
29+
```
30+
31+
## How it works
32+
33+
- The function takes an array of integers `arr` as an argument.
34+
- The function runs a for loop in `i` until the second last element. This is due to the fact that on every iteration of the `i` loop, the last `i` elements are sorted. Therefore, running the `i` loop for the first element is unnecessary.
35+
- The inner loop runs in `j` and will traverse `arr` from the start to the `n - i`th position since the last `i` elements are sorted.
36+
- The function terminates with the sorted `arr`.
37+
- The function will also work for those arrays that have duplicate elements.
38+
39+
## References
40+
41+
- [GeeksForGeeks](https://www.geeksforgeeks.org/bubble-sort/)
42+
43+
## Problem Added By
44+
45+
- [GitHub](https://www.github.com/khairalanam)
46+
- [LinkedIn](https://www.linkedin.com/in/khair-alanam-b27b69221/)
47+
- [Twitter](https://twitter.com/khair_alanam)
48+
49+
## Contributing
50+
51+
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

0 commit comments

Comments
 (0)