Skip to content

Commit 4d8d21f

Browse files
committed
Add compare callback
1 parent 124eba2 commit 4d8d21f

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/sorting/insertionsort/recursive-insertionsort.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
'use strict';
44

5+
function compare(a, b) {
6+
return a - b;
7+
}
8+
59
/**
610
* Recursive version of insertionsort. Complexity O(n^2).
711
*
@@ -10,16 +14,17 @@
1014
* @param {number} [max] Index of the element which place we should find
1115
* in the current function call
1216
*/
13-
function recursiveInsertionSort(array, max) {
17+
function recursiveInsertionSort(array, cmp, max) {
18+
cmp = cmp || compare;
1419
if (max <= 0) {
1520
return array;
1621
}
1722
if (max === undefined) {
1823
max = array.length - 1;
1924
}
20-
recursiveInsertionSort(array, max - 1);
25+
recursiveInsertionSort(array, cmp, max - 1);
2126
for (var i = max - 1, current = array[max];
22-
i >= 0 && current < array[i]; i -= 1) {
27+
i >= 0 && cmp(current, array[i]) < 0; i -= 1) {
2328
array[i + 1] = array[i];
2429
}
2530
array[i + 1] = current;

0 commit comments

Comments
 (0)