Movatterモバイル変換


[0]ホーム

URL:


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

Commitbfb9cb1

Browse files
committed
adding more optimal solution to bubble sort
1 parent1c3494c commitbfb9cb1

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-
letarr=Array.from({length:20},()=>Math.floor(Math.random()*20))
2-
console.log(arr);
1+
letarr=Array.from({length:20},()=>Math.floor(Math.random()*20))
2+
// console.log(arr);
3+
vararray1=[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(leti=0;i<arr.length;i++){
1617
for(letj=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
returnarr;
2324
}
2425

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

2728
bubbleSortBasicDescending=(arr)=>{
2829

2930
for(leti=0;i<arr.length;i++){
3031
for(letj=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
returnarr;
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+
letswapped;
48+
49+
do{
50+
swapped=false;
51+
for(leti=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+
returnarr;
59+
}
60+
61+
62+
console.log(bubbleSortAscending(array1));

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp