Advertisement
Guest User

Untitled

a guest
Jul 16th, 2013
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. using System;
  2.  
  3. class Program
  4. {
  5.  
  6.  
  7. static void MergeSort(int[] aArray)
  8. {
  9. int n = aArray.Length;
  10. int half = (n / 2);
  11.  
  12.  
  13. int[] bArray = new int[half];
  14. int[] cArray = new int[n - half];
  15.  
  16. if (n > 1)
  17. {
  18. for (int b = 0; b < half; b++)
  19. {
  20. bArray[b] = aArray[b];
  21.  
  22. }
  23. for (int c = 0; c < n - half; c++)
  24. {
  25. cArray[c] = aArray[c + half];
  26. }
  27.  
  28.  
  29. MergeSort(bArray);
  30. MergeSort(cArray);
  31. Merge(bArray, cArray, aArray, half, n);
  32. }
  33.  
  34. }
  35.  
  36. static void Merge(int[] bArray, int[] cArray, int[] aArray, int half, int n)
  37. {
  38. int i = 0;
  39. int j = 0;
  40. int k = 0;
  41.  
  42. while ((i < half) && (j < n - half))
  43. {
  44. if (bArray[i] <= cArray[j])
  45. {
  46. aArray[k] = bArray[i];
  47. i++;
  48. }
  49. else
  50. {
  51. aArray[k] = cArray[j];
  52. j++;
  53. }
  54.  
  55. k++;
  56.  
  57. if (i == half)
  58. {
  59. aArray[k] = cArray[j];
  60. }
  61. else
  62. {
  63. aArray[k] = bArray[i];
  64. }
  65.  
  66. }
  67.  
  68. }
  69.  
  70. static void Main()
  71. {
  72. int[] myArray = { 8, 3, 2, 9, 7, 1, 5, 4 };
  73.  
  74. MergeSort(myArray);
  75.  
  76. foreach (int item in myArray)
  77. {
  78. Console.Write("{0} ", item);
  79. }
  80. Console.WriteLine();
  81.  
  82.  
  83. }
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement