Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
30 additions
and
33 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,45 +1,42 @@ | ||
'use strict'; | ||
var arraySlice = require('../internals/array-slice-simple'); | ||
var arraySlice = require('../internals/array-slice'); | ||
|
||
var floor = Math.floor; | ||
|
||
var mergeSort = function (array, comparefn) { | ||
var sort = function (array, comparefn) { | ||
var length = array.length; | ||
var middle = floor(length / 2); | ||
return length < 8 ? insertionSort(array, comparefn) : merge( | ||
array, | ||
mergeSort(arraySlice(array, 0, middle), comparefn), | ||
mergeSort(arraySlice(array, middle), comparefn), | ||
comparefn | ||
); | ||
}; | ||
|
||
var insertionSort = function (array, comparefn) { | ||
var length = array.length; | ||
var i = 1; | ||
var element, j; | ||
if (length < 8) { | ||
// insertion sort | ||
var i = 1; | ||
var element, j; | ||
|
||
while (i < length) { | ||
j = i; | ||
element = array[i]; | ||
while (j && comparefn(array[j - 1], element) > 0) { | ||
array[j] = array[--j]; | ||
while (i < length) { | ||
j = i; | ||
element = array[i]; | ||
while (j && comparefn(array[j - 1], element) > 0) { | ||
array[j] = array[--j]; | ||
} | ||
if (j !== i++) array[j] = element; | ||
} | ||
if (j !== i++) array[j] = element; | ||
} return array; | ||
}; | ||
} else { | ||
// merge sort | ||
var middle = floor(length / 2); | ||
var left = sort(arraySlice(array, 0, middle), comparefn); | ||
var right = sort(arraySlice(array, middle), comparefn); | ||
var llength = left.length; | ||
var rlength = right.length; | ||
var lindex = 0; | ||
var rindex = 0; | ||
|
||
var merge = function (array, left, right, comparefn) { | ||
var llength = left.length; | ||
var rlength = right.length; | ||
var lindex = 0; | ||
var rindex = 0; | ||
while (lindex < llength || rindex < rlength) { | ||
array[lindex + rindex] = (lindex < llength && rindex < rlength) | ||
? comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++] | ||
: lindex < llength ? left[lindex++] : right[rindex++]; | ||
} | ||
} | ||
|
||
while (lindex < llength || rindex < rlength) { | ||
array[lindex + rindex] = (lindex < llength && rindex < rlength) | ||
? comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++] | ||
: lindex < llength ? left[lindex++] : right[rindex++]; | ||
} return array; | ||
return array; | ||
}; | ||
|
||
module.exports = mergeSort; | ||
module.exports = sort; |