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 41705e6

Browse files
authored
Merge pull request #34 from bexis13/print
add last console printing to show after sorting
2 parents b0a49fd + 28343d2 commit 41705e6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎Sorts/bubblesort.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
/*Bubble Sort is a algorithm to sort an array. It
22
* compares adjacent element and swaps thier position
3+
* The big O on bubble sort in worst and best case is O(N^2).
4+
* Not efficient.
35
*/
46
function bubbleSort(items) {
57
var length = items.length;
@@ -21,7 +23,44 @@ function bubbleSort(items) {
2123

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

0 commit comments

Comments
(0)

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