Skip to content

Commit 5895bf5

Browse files
Merge pull request #89 from wakidurrahman/feat/codeing-challenges-001
Feat/coding challenges 001
2 parents 46e15bc + a8e7286 commit 5895bf5

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

src/code-challenges/bubble-sort.js

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,11 @@
66

77
// Normal
88
function bubbleSortVariationNormal(arr) {
9+
const len = arr.length - 1;
910
let swaps;
1011
do {
1112
swaps = false;
12-
for (let i = 0; i < arr.length - 1; i++) {
13-
const element = arr[i];
14-
console.log(element);
13+
for (let i = 0; i < len; i++) {
1514
if (arr[i] > arr[i + 1]) {
1615
// start with the first two elements and sort them in ascending order. (Compare the element to check which one is greater).
1716
let temp = arr[i + 1]; // store second element for swap
@@ -26,3 +25,24 @@ function bubbleSortVariationNormal(arr) {
2625
}
2726

2827
bubbleSortVariationNormal([6, 5, 3, 1, 8, 7, 2, 4]);
28+
29+
// Recursively
30+
const bubbleSortVariationRecursive = function (array, pointer = array.length - 1) {
31+
// Base check
32+
if (pointer === 0) {
33+
return array;
34+
}
35+
36+
for (let i = 0; i < pointer; i++) {
37+
if (array[i] > array[i + 1]) {
38+
let temp = array[i + 1];
39+
array[i + 1] = array[i];
40+
array[i] = temp;
41+
}
42+
}
43+
44+
// Recursive call on smaller portion of the array
45+
return bubbleSortVariationRecursive(array, pointer - 1);
46+
};
47+
48+
bubbleSortVariationRecursive([6, 5, 3, 1, 8, 7, 2, 4]);

0 commit comments

Comments
 (0)