Talk about merge sort

Foreword

  • Sure enough, as the cumulative amount of multi-code, the focusing algorithms and data structures. The reason for this is because you want to have more gold content of the works produced, rather than producing a pile can not be maintained, unreadable garbage. In this way, not only to see himself this uncomfortable, others in maintaining your code when. Greeting words certainly missed.

  • Merge sort, by definition, the array has been sorted, merged together. So called merge sort.

  • Algorithm thinking

    • The n records of length n as an ordered sub-table 1
    • Normalized pairwise key and recording order to obtain the n / 2 sub-table length ordered 2
    • Repeat Step merge into one knows all records ordered length n subtable
1
2
3
4
5
6
7
8
9
10
11
12
13
function  (arr) {
if (arr.length < 2) return arr
const mid = parseInt(arr.length >>> 1)
let subLeft = mergeSort(arr.slice(0, mid))
let subRight = mergeSort(arr.slice(mid))
return merge(subLeft, subRight)
}
function merge (node1, node2) {
let result = []
while (node1.length > 0 && node2.length > 0)
result.push(node1[0] < node2[0] ? node1.shift() : node2.shift())
return result.concat(node1.length? node1 : node2)
}

Original: Big Box  talk merge sort


Guess you like

Origin www.cnblogs.com/petewell/p/11584861.html