排序算法-归并排序
自底向下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _010_归并排序 { class Program { static void Main(string[] args) { int[] data = new int[] { 42, 20, 17, 27, 13, 8, 17, 48, 65 }; mergeSort(data, 0, data.Length - 1); for (int i = 0; i < data.Length; i++) { Console.Write(data[i] + " "); } } public static void mergearray(int[] arrayData,int low,int mid,int high) { int[] aux = new int[high - low + 1]; int i = low;//左指针 int j = mid + 1;//右指针 int k = 0;//临时数组指针 //把较小的数先移动新数组中 while (i<=mid && j<=high) { if (arrayData[i] <= arrayData[j]) { aux[k++] = arrayData[i++]; } else { aux[k++] = arrayData[j++]; } } //把左边剩余的数移入数组 while (i<=mid) { aux[k++] = arrayData[i++]; } //把右边边剩余的数移入数组 while (j <= high) { aux[k++] = arrayData[j++]; } // 把新数组中的数覆盖原数组 for (int t = 0; t < aux.Length; t++) { arrayData[t+low] = aux[t]; } } /// <summary> /// 自顶向下的归并排序 /// </summary> /// <param name="arrayData"></param> /// <param name="low"></param> /// <param name="high"></param> public static void mergeSort(int[] arrayData,int low,int high) { if (low < high) { int mid = low + (high - low) / 2; //左边 mergeSort(arrayData, low, mid); //右边 mergeSort(arrayData, mid+1,high); //左右并归 mergearray(arrayData, low, mid, high); } }
自底向上:
/// <summary> /// 自底向上的归并排序 /// </summary> /// <param name="arrayData"></param> /// <param name="low"></param> /// <param name="high"></param> public static void mergeSort_2(int[] arrayData, int low, int high) { int N = arrayData.Length; for (int i = 1; i < N;i=i+i)//增量的数组 { for (int j = 0; j < N-i; j+=i+i)//每个增量比较的次数 { mergearray(arrayData,j,j+i-1,Math.Min(j+i+i-1,N-1)); } } }