Skip to content

Commit 0e6fe75

Browse files
committed
Merge pull request #54 from gauravmittal1995/master
Improving efficiency of bubblesort.
2 parents bb8367f + 3405da4 commit 0e6fe75

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

algorithms/sorting/bubble_sort.js

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,10 @@ var Comparator = require('../../util/comparator');
2626
* Bubble sort algorithm O(n^2)
2727
*/
2828
var bubbleSort = function (a, comparatorFn) {
29-
var comparator = new Comparator(comparatorFn),
30-
n = a.length,
31-
bound = n - 1;
29+
var comparator = new Comparator(comparatorFn);
30+
var n = a.length;
31+
var bound = n - 1;
32+
var check = 0;
3233
for (var i = 0; i < n - 1; i++) {
3334
var newbound = 0;
3435
for (var j = 0; j < bound; j++) {
@@ -37,11 +38,13 @@ var bubbleSort = function (a, comparatorFn) {
3738
a[j] = a[j + 1];
3839
a[j + 1] = tmp;
3940
newbound = j;
41+
check = 1;
4042
}
4143
}
44+
if (0 === check)
45+
return a;
4246
bound = newbound;
4347
}
44-
4548
return a;
4649
};
4750

0 commit comments

Comments
 (0)