二路归并排序

作者:追风剑情 发布于:2014-10-31 22:11 分类:Algorithms

时间复杂度为nlog2n.gif, 且是稳定的。


开发工具 Visual Studio

开发语言 C#

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace MergeSortTest
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. int[] R = new int[] { 75, 87, 68, 92, 88, 61, 77, 96, 80, 72 };
  13. Console.Write("排序前:");
  14. Printf(R);
  15.  
  16. MergeSort(R);
  17.  
  18. Console.WriteLine();
  19. Console.Write("排序后:");
  20. Printf(R);
  21.  
  22. Console.Read();
  23. }
  24.  
  25. static void Printf(int[] R)
  26. {
  27. for (int i = 0; i < R.Length; i++)
  28. Console.Write(R[i]+" ");
  29. }
  30.  
  31. //一次归并,将两个有序表归并为一个有序表
  32. static void Merge(int[] R, int low, int mid, int high)
  33. {
  34. int[] R1 = new int[R.Length];
  35. int i = low, j = mid + 1, k = 0;
  36. while(i<=mid && j<=high){
  37. if(R[i] <= R[j]){
  38. R1[k] = R[i];
  39. i++; k++;
  40. }else{
  41. R1[k] = R[j];
  42. j++; k++;
  43. }
  44. }
  45.  
  46. while(i<=mid){
  47. R1[k] = R[i];
  48. i++; k++;
  49. }
  50.  
  51. while (j <= high)
  52. {
  53. R1[k] = R[j];
  54. j++; k++;
  55. }
  56.  
  57. for (k = 0, i = low; i <= high; k++, i++)
  58. R[i] = R1[k];
  59. }
  60.  
  61. //一趟归并
  62. static void MergePass(int[] R, int length)
  63. {
  64. int n = R.Length;
  65. int i;
  66. //归并length长的两个相邻子表
  67. for (i = 0; i + 2 * length - 1 < n; i = i + 2 * length)
  68. Merge(R, i, i+length-1, n-1);
  69.  
  70. //余下两个子表,后者长度小于length
  71. if (i + length - 1 < n)
  72. Merge(R, i, i+length-1, n-1);//归并这两个子表
  73. }
  74.  
  75. //二路归并排序
  76. static void MergeSort(int[] R)
  77. {
  78. int n = R.Length;
  79. int length;
  80. for (length = 1; length < n; length = 2 * length)
  81. MergePass(R, length);
  82. }
  83. }
  84. }

运行结果

megersort.png

标签: Algorithms

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号