Skip to content

Commit e955209

Browse files
author
wakidurrahman
committed
feat: bubbleSortVariationNormal
1 parent 5d0e476 commit e955209

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/code-challenges/bubble-sort.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* 001: Bubble Sort: is based on the idea of repeatedly comparing pairs of adjacent elements and
3+
* then swapping their positions if they are in the wrong order.
4+
* Bubble sort is a stable, in-place sort algorithm.
5+
*/
6+
7+
// Normal
8+
function bubbleSortVariationNormal(arr) {
9+
let swaps;
10+
do {
11+
swaps = false;
12+
for (let i = 0; i < arr.length - 1; i++) {
13+
const element = arr[i];
14+
console.log(element);
15+
if (arr[i] > arr[i + 1]) {
16+
// start with the first two elements and sort them in ascending order. (Compare the element to check which one is greater).
17+
let temp = arr[i + 1]; // store second element for swap
18+
arr[i + 1] = arr[i]; // Swap first element to second element
19+
arr[i] = temp; // // Swap second element to first element
20+
swaps = true; // true for loop continue until Compare not false condition
21+
}
22+
}
23+
} while (swaps);
24+
25+
return arr;
26+
}
27+
28+
bubbleSortVariationNormal([6, 5, 3, 1, 8, 7, 2, 4]);

0 commit comments

Comments
 (0)