Advertisement
Guest User

MergeSort

a guest
Dec 20th, 2013
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. using System;
  2.  
  3. namespace _13MergeSort
  4. {
  5. class MergeSort
  6. {
  7. static void Main()
  8. {
  9. int length;
  10. bool correct;
  11. do
  12. {
  13. Console.WriteLine("Please input the length of the array");
  14. correct = int.TryParse(Console.ReadLine(), out length) && length > 0;
  15. if (!correct)
  16. {
  17. Console.WriteLine("This is not a correct number!");
  18. }
  19. } while (!correct);
  20. int[] array = new int[length];
  21. Console.WriteLine("Please input the integer numbers of the array.");
  22. for (int i = 0; i < length; i++)
  23. {
  24. array[i] = int.Parse(Console.ReadLine());
  25. }
  26. Console.WriteLine("The array is:");
  27. Console.WriteLine(String.Join(", ", array));
  28. array = Sort(array);
  29. Console.WriteLine("The sorted array is:");
  30. Console.WriteLine(String.Join(", ", array));
  31. }
  32.  
  33. static int[] Sort(int[] array)
  34. {
  35. if (array.Length < 2)
  36. {
  37. return array;
  38. }
  39. int middle = array.Length / 2;
  40. int[] left = new int[middle];
  41. for (int i = 0; i < left.Length; i++)
  42. {
  43. left[i] = array[i];
  44. }
  45. int[] right = new int[array.Length - middle];
  46. for (int i = 0; i < right.Length; i++)
  47. {
  48. right[i] = array[middle + i];
  49. }
  50.  
  51. Sort(left);
  52. Sort(right);
  53.  
  54. int leftIndex = 0;
  55. int rightIndex = 0;
  56. for (int i = 0; i < array.Length; i++)
  57. {
  58. if (leftIndex < left.Length && rightIndex < right.Length)
  59. {
  60. if (left[leftIndex] <= right[rightIndex])
  61. {
  62. array[i] = left[leftIndex];
  63. leftIndex++;
  64. }
  65. else
  66. {
  67. array[i] = right[rightIndex];
  68. rightIndex++;
  69. }
  70. }
  71. else if (leftIndex == left.Length)
  72. {
  73. array[i] = right[rightIndex];
  74. rightIndex++;
  75. }
  76. else
  77. {
  78. array[i] = left[leftIndex];
  79. leftIndex++;
  80. }
  81. }
  82. return array;
  83. }
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement