File tree Expand file tree Collapse file tree 1 file changed +17
-1
lines changed Expand file tree Collapse file tree 1 file changed +17
-1
lines changed Original file line number Diff line number Diff line change
1
+ // tag::merge[]
2
+ /**
3
+ * Merge two arrays in ascending order
4
+ * @param {Array} array1
5
+ * @param {Array} array2
6
+ */
1
7
function merge(array1, array2 = []) {
2
8
const mergedLength = array1.length + array2.length;
3
9
const mergedArray = Array(mergedLength);
@@ -6,29 +12,39 @@ function merge(array1, array2 = []) {
6
12
if (i2 >= array2.length || (i1 < array1.length && array1[i1] <= array2[i2])) {
7
13
mergedArray[index] = array1[i1];
8
14
i1 += 1;
9
- } else if (i1 >= array1.length || (i2 < array2.length && array2[i2] <= array1[i1])) {
15
+ } else {
10
16
mergedArray[index] = array2[i2];
11
17
i2 += 1;
12
18
}
13
19
}
14
20
15
21
return mergedArray;
16
22
}
23
+ // end::merge[]
17
24
25
+ // tag::splitSort[]
26
+ /**
27
+ * Split array in half until two or less elements are left.
28
+ * Sort these two elements and combine them back using the merge function.
29
+ * @param {Array} array
30
+ */
18
31
function splitSort(array) {
19
32
const size = array.length;
33
+
20
34
if (size < 2) {
21
35
return array;
22
36
} else if (size === 2) {
23
37
return array[0] < array[1] ? array : [array[1], array[0]];
24
38
}
39
+
25
40
const middle = Math.ceil(size / 2);
26
41
27
42
return merge(
28
43
splitSort(array.slice(0, middle)),
29
44
splitSort(array.slice(middle)),
30
45
);
31
46
}
47
+ // end::splitSort[]
32
48
33
49
// tag::sort[]
34
50
/**
You can’t perform that action at this time.
0 commit comments