归并排序——算法系列
归并排序:
主要思想是,将一列无序数,无限分组,直至分成单个元素,然后归并,因为归并前,两组数据都已经有序,所以复杂度要小。
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { class Program { static void Main(string[] args) { int[] array = { 3, 1, 2, 9, 7, 8, 6 }; Console.WriteLine("排序前:" + string.Join(",", array)); MergeSort(array, new int[array.Length], 0, array.Length - 1); Console.WriteLine("排序后:" + string.Join(",", array)); Console.ReadLine(); } static void MergeSort(int[] array, int[] temparray, int left, int right) { if (left < right) { int middle = (left + right) / 2; MergeSort(array, temparray, left, middle); MergeSort(array, temparray, middle + 1, right); Merge(array, temparray, left, middle + 1, right); } } static void Merge(int[] array, int[] temparray, int left, int middle, int right) { int leftEnd = middle - 1; int rightStart = middle; int tempIndex = left; int tempLength = right - left + 1; while (left <= leftEnd && rightStart <= right) { if (array[left] < array[rightStart]) temparray[tempIndex++] = array[left++]; else temparray[tempIndex++] = array[rightStart++]; } while (left <= leftEnd) temparray[tempIndex++] = array[left++]; while (rightStart <= right) temparray[tempIndex++] = array[rightStart++]; for (int i = 0; i < tempLength; i++) { array[right] = temparray[right]; right--; } } } }
总结:这个归并排序还是要重新看下,没有怎么理解到其中的精髓。