合并排序
具体原理可看这里
javascript版本:
function merge(left, right){ var result = []; while (left.length > 0 && right.length > 0){ if (left[0] < right[0]){ result.push(left.shift());//把最小的最先取出,放到结果集中 } else { result.push(right.shift()); } } return result.concat(left).concat(right);//剩下的就是合并,这样就排好序了 } function mergeSort(array){ if (array.length == 1) { return array; } var middle = Math.floor(array.length / 2),//求出中点 left = array.slice(0, middle),//分割数组 right = array.slice(middle); return merge(mergeSort(left), mergeSort(right));//递归合并与排序 }
ruby版本:
def merge(left, right) final = [] until left.empty? or right.empty? final << ( left.first < right.first ? left.shift : right.shift ) end final + left + right end def mergeSort(array) return array if array.size < 2 left = array.first(array.size/2) right = array.last(array.size - array.size/2) merge(mergeSort(left), mergeSort(right)) end
机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年