且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mergesort算法实现

更新时间:2023-02-26 18:04:57

合并排序的工作方式是将未排序的数据分解为单个元素,单个元素被视为已排序,然后将它们合并为更大的排序后的大块.

Merge sort works by splitting the unsorted data down into individual elements, a single element being considered sorted, and merging them back together in progrssively larger sorted chunks.

b数组是实现中的工作台",并且在每次迭代(示例中为递归)结束时,保存该迭代的工作结果.通过将未排序的数组的左侧和右侧复制到b数组中来执行拆分.

The b array is the 'work bench' in your implementation and, at the end of each iteration (recursion in your example), holds the result of the work done that iteration. The split is peformed by copying the left and right sides of the unsorted array into the b array.

为了在拆分数组后备份"时构建合并结果,需要从组件重建结果,方法是将排序后的块复制回未排序的原始块.

In order to build the merged result as you come 'back up' from splitting the array, you need to rebuild the result from the components, which is done by copying the sorted chunk back over it's unsorted original.

如果更改了递归,则合并的方向(从左到右或从右到左/从低到高或从高到低)与递归的级别相对应,可以避免复制.没有b数组的完全原位复制合并排序是一个更复杂的算法.

The copy can be avoided if the recursion is changed so that the direction of the merge (left to right or right to left / low to high or high to low) corresponds with the level of the recursion. Full copy-in-place merge sort, without the b array, is a more complicated alogrithm.