算法:合并排序(Merge Sort)
2013-12-06 09:06
369 查看
算法定义
合并排序是一种递归算法,思路如下:
如果源数组长度为 1,立即返回。
将源数组平分为两个新数组:Left 和 Right。
对 Left 执行递归排序。
对 Right 执行递归排序。
将排序后的 Left 和 Right 执行合并到原数组。
可以看出来,改算法的重点是已排序数组的合并过程。
算法举例
【5,4,3,2,1】
【5,4,3】【2,1】
【5,4】【3】【2,1】
【5】【4】【3】【2,1】
【4,5】【3】【2,1】
【3,4,5】【2,1】
【3,4,5】【2】【1】
【3,4,5】【1,2】
【1,2,3,4,5】
算法实现
合并过程
已排序数组的合并过程比较有意思,分别对 Left 和 Right 维护一个从左到右的指针,分别是:leftIndex 和 RightIndex,当填充目标数组的第 i 个元素时,需要从 Left 和 Right 中找到剩余元素(指针到末尾部分的元素)的最小值,因为是已排序数组,只需比较 Left[LeftIndex] 和 Right[RightIndex] 的大小,将最小的元素填充到目标数组的第 i 个位置即可,然后相应的指针加 1。
合并排序是一种递归算法,思路如下:
如果源数组长度为 1,立即返回。
将源数组平分为两个新数组:Left 和 Right。
对 Left 执行递归排序。
对 Right 执行递归排序。
将排序后的 Left 和 Right 执行合并到原数组。
可以看出来,改算法的重点是已排序数组的合并过程。
算法举例
【5,4,3,2,1】
【5,4,3】【2,1】
【5,4】【3】【2,1】
【5】【4】【3】【2,1】
【4,5】【3】【2,1】
【3,4,5】【2,1】
【3,4,5】【2】【1】
【3,4,5】【1,2】
【1,2,3,4,5】
算法实现
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataStuctureStudy.Sorts { class MergeSort<T> where T : IComparable<T> { private static void Swap(T[] items, int left, int right) { if (left != right) { var temp = items[left]; items[left] = items[right]; items[right] = temp; } } public static void Sort(T[] items) { if (items.Length < 2) { return; } int leftSize = items.Length / 2; int rightSize = items.Length - leftSize; T[] left = new T[leftSize]; T[] right = new T[rightSize]; Array.Copy(items, 0, left, 0, leftSize); Array.Copy(items, leftSize, right, 0, rightSize); Sort(left); Sort(right); Merge(items, left, right); } private static void Merge(T[] items, T[] left, T[] right) { var leftIndex = 0; var rightIndex = 0; for (var i = 0; i < items.Length; i++) { if (leftIndex >= left.Length) { items[i] = right[rightIndex]; rightIndex++; } else if (rightIndex >= right.Length) { items[i] = left[leftIndex]; leftIndex++; } else if (left[leftIndex].CompareTo(right[rightIndex]) < 0) { items[i] = left[leftIndex]; leftIndex++; } else { items[i] = right[rightIndex]; rightIndex++; } } } } }
合并过程
已排序数组的合并过程比较有意思,分别对 Left 和 Right 维护一个从左到右的指针,分别是:leftIndex 和 RightIndex,当填充目标数组的第 i 个元素时,需要从 Left 和 Right 中找到剩余元素(指针到末尾部分的元素)的最小值,因为是已排序数组,只需比较 Left[LeftIndex] 和 Right[RightIndex] 的大小,将最小的元素填充到目标数组的第 i 个位置即可,然后相应的指针加 1。
相关文章推荐
- 合并排序连接(Merge Sort Join)-2
- 归并排序(merge sort)算法实现
- Java实现算法归并排序(MergeSort)
- 算法-排序-归并排序(MergeSort)分析
- 合并排序(归并排序 MergeSort)
- 归并排序(merge sort)算法实现
- 归并排序(Merge sort)算法
- 算法学习笔记 —— MergeSort 的一种循环实现
- 合并排序(归并排序 MergeSort)
- 算法---归并排序(Merge Sort)---多版本对比
- 归并排序(merge sort)算法实现
- 算法上机题目mergesort,priority queue,Quicksort,divide and conquer
- 简谈算法之:并归排序(Merge Sort)
- MergeSort(归并排序)算法Java实现
- 合并排序(MergeSort)
- 基本排序算法05----合并排序(merge sort)
- linux下归并排序(MergeSort)算法的C语言实现
- 【从零学习经典算法系列】分治策略实例——归并排序(Mergesort)
- 合并排序(Merge Sort)C 实现(简单性能测试)
- 【算法导论】2-2 二路归并排序(分治)merge-sort 和逆序对的问题