ljerka - 10 months ago 47

AngularJS Question

I'm trying to call a function recursively (for sorting purposes) but getting an error. I tried to find a solution and found How to call function recursively;

I changed my code accordingly, so now it looks like this:

`$scope.orderCustom = function() {`

qS.quickSort($scope.mydata, 0, mydata.length-1);

};

var qS = {

quickSort: function quickSort(data, min, max) {

if (min < max) {

var p = qSP.quickSortPartition(data, min, max);

var newMax = p-1;

var newMin = p+1;

qS.quicksort(data, min, newMax);

qS.quicksort(data, newMin, max);

}

}

};

var qSP = {

quickSortPartition: function quickSortPartition(data, min, max) {

var pivot = data[max].id;

var i = min;

for (var j = min; j <= max; j++) {

if (data[j].id <= pivot) {

var pom = data[j];

data[j] = data[i];

data[i] = pom;

i = i+1;

}

}

var pom = data[i];

data[i] = data[max];

data[max] = pom;

return i;

}

};

I'm getting an error "Error: qS.quicksort is not a function". Does anyone know how to solve this problem?

I am still not able to leave a comment on stackoverflow, so I had to open a new question for this. Any help would be appriciated. Thanx :)

Answer Source

The simplest thing would be to get rid of the extra wrapping and just use the functions:

```
$scope.orderCustom = function() {
quickSort($scope.mydata, 0, mydata.length-1);
};
function quickSort(data, min, max) {
if (min < max) {
var p = quickSortPartition(data, min, max);
var newMax = p-1;
var newMin = p+1;
quickSort(data, min, newMax);
quickSort(data, newMin, max);
}
}
function quickSortPartition(data, min, max) {
var pivot = data[max].id;
var i = min;
for (var j = min; j <= max; j++) {
if (data[j].id <= pivot) {
var pom = data[j];
data[j] = data[i];
data[i] = pom;
i = i+1;
}
}
var pom = data[i];
data[i] = data[max];
data[max] = pom;
return i;
}
```

Note that you also have to correct the spelling of the recursive call `quickSort`

as you had used all lower case `quicksort`

.

I assume this is just a programming exercise as you would be better for real code to use the built-in `sort()`

function or for angular you might prefer the `orderBy`

filter.

For example, this does the same as you look to be trying to do:

```
function compare(a,b) {
if (a.id < b.id)
return -1;
if (a.id > b.id)
return 1;
return 0;
}
$scope.mydata.sort(compare);
```