Guest User

Untitled

a guest
Oct 20th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1.  
  2. public class MergeSorter2
  3. {
  4. private int[] a;
  5.  
  6. public MergeSorter2(int[] anArray)
  7. {
  8. a = anArray;
  9. }
  10.  
  11. public void sort()
  12. {
  13. if(a.length<=1) return;
  14.  
  15. int[] first = new int[a.length/3];
  16. int[] second = new int[first.length];
  17. int[] third = new int[a.length-(2*second.length)];
  18.  
  19. for(int i=0;i<first.length;i++)
  20. {
  21. first[i]=a[i];
  22. }
  23. for(int i=0; i<second.length;i++)
  24. {
  25. second[i]=a[first.length+i];
  26. }
  27. for(int i=0; i<third.length;i++)
  28. {
  29. third[i]=a[second.length+i];
  30. }
  31.  
  32. MergeSorter2 firstSorter = new MergeSorter2(first);
  33. MergeSorter2 secondSorter = new MergeSorter2(second);
  34. MergeSorter2 thirdSorter = new MergeSorter2(third);
  35.  
  36. firstSorter.sort();
  37. secondSorter.sort();
  38. thirdSorter.sort();
  39.  
  40. merge(first, second, third);
  41. }
  42.  
  43. public void merge(int[] first, int[] second, int[] third)
  44. {
  45. int iFirst=0, iSecond=0, iThird=0, j=0;
  46.  
  47. while(iFirst<first.length && iSecond<second.length && iThird<third.length)
  48. {
  49. if(first[iFirst]<second[iSecond] && first[iFirst]<third[iThird])
  50. {
  51. a[j]=first[iFirst];
  52. iFirst++;
  53. }
  54. else if(second[iSecond]<first[iFirst] && second[iSecond]<third[iThird])
  55. {
  56. a[j]=second[iSecond];
  57. iSecond++;
  58. }
  59. else
  60. {
  61. a[j] = third[iThird];
  62. iThird++;
  63. }
  64. j++;
  65. }
  66.  
  67. while(iFirst<first.length)
  68. {
  69. a[j]=first[iFirst];
  70. j++; iFirst++;
  71. }
  72. while(iSecond<second.length)
  73. {
  74. a[j]=second[iSecond];
  75. j++; iSecond++;
  76. }
  77. while(iThird<third.length)
  78. {
  79. a[j]=third[iThird];
  80. j++; iThird++;
  81. }
  82. }
  83. }
Add Comment
Please, Sign In to add comment