var array = [1, 9, 2, 1, 5, 2, 3, 7, 7]
console.log('== 归并排序 ==\n')
console.log(`归并排序是第一个可以被实际使用的排序算法。你在本书中学到的前三个排序算法(冒泡、选择、插入)性能不
好,但归并排序性能不错,其复杂度为O(nlogn)。\n`)
console.log(`归并排序是一种分治算法。其思想是将原始数组切分成较小的数组,直到每个小数组只有一
个位置,接着将小数组归并成较大的数组,直到最后只有一个排序完毕的大数组。\n`)
function createRandomArray(size) {
var arr = []
for (let i = 0; i < size; i++) {
arr.push(Math.round(Math.random() * size))
}
array = arr
return arr
}
function mergeSort() {
}
function merge1(left, right) {
var result = []
var shiftL = left.shift()
var shiftR = right.shift()
while (shiftL != undefined || shiftR != undefined) {
if (shiftL !== undefined && shiftR !== undefined) {
if (shiftL >= shiftR) {
result.push(shiftR)
shiftR = right.shift()
} else {
result.push(shiftL)
shiftL = left.shift()
}
}
if (shiftL != undefined && shiftR == undefined) {
result.push(shiftL)
shiftL = left.shift()
}
if (shiftR != undefined && shiftL == undefined) {
result.push(shiftR)
shiftR = right.shift()
}
}
return result
}
function merge(left, right) {
var result = [],
il = 0,
ir = 0
while (il < left.length && ir < right.length) {
if (left[il] < right[ir]) {
result.push(left[il++])
} else {
result.push(right[ir++])
}
}
while (il < left.length) {
result.push(left[il++])
}
while (ir < left.length) {
result.push(right[ir++])
}
return result
}
function mergeSortRec(array, num) {
var len = array.length
if (len == 1) {
return array
}
var mid = Math.floor(len / 2),
left = array.slice(0, mid),
right = array.slice(mid, len)
if (num) {
return merge1(mergeSortRec(left), mergeSortRec(right))
} else {
return merge(mergeSortRec(left), mergeSortRec(right))
}
}
createRandomArray(9)
array = [1, 3, 7, 6, 7, 8, 9, 2, 3]
console.log('排序前:', array)
console.time('耗时')
array = mergeSortRec(array)
console.timeEnd('耗时')
console.log('排序后数组:', array)
console.log('\n')
createRandomArray(9)
array = [1, 3, 7, 6, 7, 8, 9, 2, 3]
console.log('排序前:', array)
console.time('耗时1')
array = mergeSortRec(array, 1)
console.timeEnd('耗时1')
console.log('排序后数组:', array)