ellapt

T7.13.MergeSort

Jan 15th, 2013
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. using System;
  2. class MergeSort
  3. {
  4. static void MergeSortInt(int arrLen, int[] arrInt)
  5. {
  6. int cnt = arrLen;
  7. if (cnt == 2)
  8. {
  9. int tmp;
  10. if (arrInt[0] > arrInt[1])
  11. {
  12. tmp = arrInt[0];
  13. arrInt[0] = arrInt[1];
  14. arrInt[1] = tmp;
  15. }
  16. }
  17. else if (cnt > 2)
  18. {
  19. cnt = arrLen / 2;
  20. int[] leftSide = new int[cnt];
  21. int[] rightSide = new int[cnt + 1];
  22. for (int i = 0; i < cnt; i++)
  23. {
  24. leftSide[i] = arrInt[i];
  25. }
  26. for (int i = cnt; i < arrLen; i++)
  27. {
  28. rightSide[i - cnt] = arrInt[i];
  29. }
  30.  
  31. MergeSortInt(cnt, leftSide);
  32. MergeSortInt(arrLen - cnt, rightSide);
  33.  
  34. int leftIndx = 0;
  35. int rightIndx = 0;
  36. while ((leftIndx + rightIndx) < arrLen)
  37. {
  38. if (leftIndx == cnt)
  39. arrInt[leftIndx + rightIndx] = rightSide[rightIndx++];
  40. else if (rightIndx == (arrLen-cnt))
  41. arrInt[leftIndx + rightIndx] = leftSide[leftIndx++];
  42. else
  43. arrInt[leftIndx + rightIndx] = (leftSide[leftIndx] < rightSide[rightIndx]? leftSide[leftIndx++]: rightSide[rightIndx++]);
  44.  
  45. }
  46. }
  47. }
  48.  
  49. static void Main()
  50. {
  51. Console.WriteLine("Sort an array of integers using the MergeSort algorithm");
  52. Console.Write("Enter array length: ");
  53. int n = int.Parse(Console.ReadLine());
  54. Console.WriteLine("Enter the array elements: ");
  55. int[] arrOfInt = new int[n];
  56. for (int i = 0; i < n; i++)
  57. {
  58. arrOfInt[i] = int.Parse(Console.ReadLine());
  59. }
  60.  
  61. MergeSortInt(n, arrOfInt);
  62.  
  63. Console.WriteLine("The sorted array is:");
  64. for (int i = 0; i < n; i++)
  65. {
  66. Console.Write("{0} ",arrOfInt[i]);
  67. }
  68. Console.WriteLine();
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment