Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bfb9cb1

Browse files
adding more optimal solution to bubble sort
1 parent 1c3494c commit bfb9cb1

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

‎Sorting/bubble-sort-basic.js‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
let arr = Array.from({length: 20}, () => Math.floor(Math.random() * 20))
2-
console.log(arr);
1+
let arr = Array.from({ length: 20}, () => Math.floor(Math.random() * 20))
2+
// console.log(arr);
3+
var array1 = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
34

45
// swap helper function
56
swap = (arr, i, j) => {
@@ -15,25 +16,47 @@ bubbleSortBasicAscending = (arr) => {
1516
for (let i = 0; i < arr.length; i++) {
1617
for (let j = 1; j < arr.length; j++) {
1718
if (arr[j] < arr[j - 1]) {
18-
swap(arr, j, j-1);
19+
swap(arr, j, j-1);
1920
}
2021
}
2122
}
2223
return arr;
2324
}
2425

25-
console.log(bubbleSortBasicAscending(arr));
26+
console.log(bubbleSortBasicAscending(array1));
2627

2728
bubbleSortBasicDescending = (arr) => {
2829

2930
for (let i = 0; i < arr.length; i++) {
3031
for (let j = 1; j < arr.length; j++) {
3132
if (arr[j] > arr[j - 1]) {
32-
swap(arr, j, j-1);
33+
swap(arr, j, j-1);
3334
}
3435
}
3536
}
3637
return arr;
3738
}
3839

39-
console.log(bubbleSortBasicDescending(arr));
40+
console.log(bubbleSortBasicDescending(array1));
41+
42+
/* A more optimal solution, by reducing some of the loop execution are not done in this solution.
43+
So, here, I only do the loops and swaps for the cases when I find a mis-placed element, i.e. larger-element placed before smaller in an ascending sort
44+
*/
45+
bubbleSortAscending = arr => {
46+
47+
let swapped;
48+
49+
do {
50+
swapped = false;
51+
for (let i = 0; i < arr.length; i++) {
52+
if (arr[i] && arr[i + 1] && (arr[i] > arr[i + 1])) {
53+
swap(arr, i, i + 1);
54+
swapped = true;
55+
}
56+
}
57+
} while (swapped)
58+
return arr;
59+
}
60+
61+
62+
console.log(bubbleSortAscending(array1));

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /