Skip to content

Commit 9dbf000

Browse files
committed
add additional implementation using a while loop for educational purposes
1 parent 0551dba commit 9dbf000

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Sorts/bubblesort.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,43 @@ function bubbleSort(items) {
2323

2424
var ar=[5,6,7,8,1,2,12,14];
2525
//Array before Sort
26+
console.log("-----before sorting-----")
2627
console.log(ar);
2728
bubbleSort(ar);
2829
//Array after sort
2930
console.log(ar);
3031

32+
/*alternative implementation of bubble sort algorithm.
33+
Using a while loop instead. For educational purposses only
34+
*/
35+
/*
36+
*In bubble sort, we keep iterating while something was swapped in
37+
*the previous inner-loop iteration. By swapped I mean, in the
38+
*inner loop iteration, we check each number if the number proceeding
39+
*it is greater than itself, if so we swap them.
40+
*/
41+
42+
function bubbleSort(arr){
43+
var swapped = true;
44+
while(swapped){
45+
var swapped = false;
46+
for(var i = 0; i < arr.length; i++){
47+
if(arr[i] > arr[i + 1]){
48+
var temp = arr[i];
49+
arr[i] = arr[i + 1];
50+
arr[i + 1] = temp;
51+
swapped = true;
52+
}
53+
}
54+
}
55+
return arr;
56+
}
57+
58+
//test
59+
console.log("-----before sorting-----")
60+
var array = [10,5,3,8,2,6,4,7,9,1];
61+
console.log(array);
62+
console.log("-----after sorting-----")
63+
console.log(bubbleSort(array));
64+
3165

0 commit comments

Comments
 (0)