[Algorithms] Divide and Recurse Over an Array with Merge Sort in JavaScript
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Algorithms] Divide and Recurse Over an Array with Merge Sort in JavaScript相关的知识,希望对你有一定的参考价值。
Merge sort is a recursive sorting algorithm. If you don‘t understand recursion, I recommend finding a resource to learn it. In brief, recursion is the act of a function calling itself. Thus, merge sort is accomplished by the algorithm calling itself to provide a solution.
Merge sort divides the given array into two halves, a left half and a right half. We call merge sort on these sub-arrays. We continue to split our sub-arrays until we get arrays whose length is less than two. We then begin to stitch our small arrays back together, sorting them on the way up.
This is an efficient algorithm because we start by sorting very small arrays. By the time we reach our larger ones, they are already mostly sorted, saving us the need for expensive loops. To create our algorithm, we‘ll actually need two functions, our mergeSort
function and a merge
function that does the combining and sorting of our sub-arrays.
Utilize javascript LIFO (last in first our queue stack to do the traverse)
For example:
left [ 2, 3, 5, 6, 10 ] right [ 1, 4, 7, 8, 9 ] reuslts [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
function mergeSort (array) { // if array is length less than two items, no need to sort if ( array.length < 2 ) { return array; } // find the middle point of the array to split it into two const middle = Math.floor(array.length / 2); const left = array.slice(0, middle); const right = array.slice(middle); return merge( mergeSort(left), mergeSort(right) ) } function merge(left, right) { let sorted = []; console.log(‘left‘, left) console.log(‘right‘, right) while (left.length && right.length) { if (left[0] < right[0]) { sorted.push(left.shift()) } else { sorted.push(right.shift()) } } const reuslts = [...sorted, ...left, ...right]; console.log(‘reuslts‘, reuslts) return reuslts; } let numbers = [10, 5, 6, 3, 2, 8, 9, 4, 7, 1] mergeSort(numbers) exports.mergeSort = mergeSort
以上是关于[Algorithms] Divide and Recurse Over an Array with Merge Sort in JavaScript的主要内容,如果未能解决你的问题,请参考以下文章
UVa 10375 Choose and divide (唯一分解定理)
UVa 10375 - Choose and divide(唯一分解定理)
UVA 10375 - Choose and divide(数论)(组合数学)