Reputation: 41
I'm new in Javascript and getting this weird issue:
When calling "bubbleSort" function from another "sort" function which supposed to clone the array and return a new sorted array - the result i get is not right.
I'll be happy to know what is the problem, I've been trying other ways to clone the array such as while loop, slice, [...a] and others and still can't understand what the problem is.
function bubbleSort(arr, compareFunction = comparator()) {
var len = arr.length;
console.log("bubble!!");
for (var i = 0; i < len; i++) {
for (var j = 0; j < len - i - 1; j++) {
if (comparator(a[j], a[j + 1]) == 1) {
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
function sort(a, sorter, compareFunction = comparator()) {
return sorter(a, comparator);
}
function sortNumbers(a) {
var arrClone = a.slice(0);
arrClone = sort(arrClone, bubbleSort);
return arrClone;
}
function comparator(a, b) { if (a < b) return -1; else if (a > b) return 1; else return 0; }
// when i'm using any of the following:
var a = [33, 103, 3, 726, 200, 984, 198, 764, 9];
console.log(bubbleSort(a));
a = [33, 103, 3, 726, 200, 984, 198, 764, 9];
console.log(bubbleSort(a, comparator));
a = [33, 103, 3, 726, 200, 984, 198, 764, 9];
console.log(sort(a, bubbleSort));
// I'm getting the desired result:
// [ 3, 9, 33, 103, 198, 200, 726, 764, 984 ]
// But when i'm using:
a = [33, 103, 3, 726, 200, 984, 198, 764, 9];
console.log(sortNumbers(a));
// I'm getting:
// [ 33, 3, 103, 200, 726, 198, 984, 9, 764 ]
when i'm using any of the following:
var a = [33, 103, 3, 726, 200, 984, 198, 764, 9];
console.log(bubbleSort(a));
console.log(bubbleSort(a, comparator));
console.log(sort(a, bubbleSort));
I'm getting the desired result:
[ 3, 9, 33, 103, 198, 200, 726, 764, 984 ]
But when i'm using:
console.log(sortNumbers(a));
I'm getting:
[ 33, 3, 103, 200, 726, 198, 984, 9, 764 ]
Upvotes: 0
Views: 71
Reputation: 129
function sort(a, sorter, compareFunction = comparator())
should be
function sort(a, sorter, compareFunction = comparator)
cause you are passing a function, no a result.
moreover you are passing it but not using, anyway
Upvotes: 1
Reputation: 28573
You have a typo where you are using a
in place of the parameter arr
, so when you .slice
, your arr
and a
are not the same thing.
function bubbleSort(arr, compareFunction = comparator()) {
//...
if (comparator(a[j], a[j + 1]) == 1) {
//...
}
var a = [33, 103, 3, 726, 200, 984, 198, 764, 9];
Upvotes: 2