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+ */
17function merge ( array1 , array2 = [ ] ) {
28 const mergedLength = array1 . length + array2 . length ;
39 const mergedArray = Array ( mergedLength ) ;
@@ -6,29 +12,39 @@ function merge(array1, array2 = []) {
612 if ( i2 >= array2 . length || ( i1 < array1 . length && array1 [ i1 ] <= array2 [ i2 ] ) ) {
713 mergedArray [ index ] = array1 [ i1 ] ;
814 i1 += 1 ;
9- } else if ( i1 >= array1 . length || ( i2 < array2 . length && array2 [ i2 ] <= array1 [ i1 ] ) ) {
15+ } else {
1016 mergedArray [ index ] = array2 [ i2 ] ;
1117 i2 += 1 ;
1218 }
1319 }
1420
1521 return mergedArray ;
1622}
23+ // end::merge[]
1724
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+ */
1831function splitSort ( array ) {
1932 const size = array . length ;
33+
2034 if ( size < 2 ) {
2135 return array ;
2236 } else if ( size === 2 ) {
2337 return array [ 0 ] < array [ 1 ] ? array : [ array [ 1 ] , array [ 0 ] ] ;
2438 }
39+
2540 const middle = Math . ceil ( size / 2 ) ;
2641
2742 return merge (
2843 splitSort ( array . slice ( 0 , middle ) ) ,
2944 splitSort ( array . slice ( middle ) ) ,
3045 ) ;
3146}
47+ // end::splitSort[]
3248
3349// tag::sort[]
3450/**
You can’t perform that action at this time.
0 commit comments