Skip to content

Commit 3f7b8fa

Browse files
committed
Moved insertion sort, updated merge sort recursive
1 parent 9528a06 commit 3f7b8fa

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

algorithms/sorting/merge-sort-recursive/merge-sort-recursive.js

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,19 @@
2929
* @return {Array} The merged array.
3030
*/
3131
function merge(left, right){
32-
var result = [];
32+
var result = [],
33+
il = 0,
34+
ir = 0;
3335

34-
while (left.length > 0 && right.length > 0){
35-
if (left[0] < right[0]){
36-
result.push(left.shift());
36+
while (il < left.length && ir < right.length){
37+
if (left[il] < right[ir]){
38+
result.push(left[il++]);
3739
} else {
38-
result.push(right.shift());
40+
result.push(right[ir++]);
3941
}
4042
}
4143

42-
return result.concat(left).concat(right);
44+
return result.concat(left.slice(il)).concat(right.slice(ir));
4345
}
4446

4547
/**
@@ -50,7 +52,7 @@ function merge(left, right){
5052
*/
5153
function mergeSort(items){
5254

53-
if (items.length == 1) {
55+
if (items.length < 2) {
5456
return items;
5557
}
5658

0 commit comments

Comments
 (0)