Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. public class MergeSort {
  2. private final int[] arr;
  3.  
  4. public MergeSort(int[] arr) {
  5. this.arr = arr;
  6. }
  7.  
  8. public int[] sort() {
  9. int start = 0;
  10. int end = arr.length - 1;
  11.  
  12. mergeSort(start, end);
  13.  
  14. return arr;
  15. }
  16.  
  17. private void mergeSort(int start, int end) {
  18. if (start < end) { // Return if start == end
  19. int mid = (start + end) / 2; // Find the mid
  20.  
  21. mergeSort(start, mid); // Do recursion with left side variables
  22. mergeSort(mid + 1, end); // Do recursion with right side variables
  23.  
  24. merge(start, mid, end); // When both of the recursion return the merge left and right variables
  25. }
  26. }
  27.  
  28. private void merge(int start, int mid, int end) {
  29. int m = (mid - start) + 1; // Size of the first array
  30. int n = (end - mid);
  31.  
  32. int[] arr1 = new int[m]; // Create the first array
  33. int[] arr2 = new int[n]; // Create the second array
  34.  
  35. int i, j, k = start;
  36.  
  37. // Copy m number of variables starting from main array starting from index start to first array
  38. for (i = 0; i < m; i++) {
  39. arr1[i] = arr[k++];
  40. }
  41.  
  42. // Copy n number of variables starting from main array staring from mid + 1 to the second array
  43. for (j = 0; j < n; j++) {
  44. arr2[j] = arr[k++];
  45. }
  46.  
  47. i = j = 0;
  48. k = start;
  49.  
  50. // Break through the while when either i become m or j becomes n
  51. while (i != m && j != n) {
  52. /*
  53. Basically it's just one kinda sort
  54. - if element from the first array is less than the element from the second array then that element should be inserted in the main array
  55. - otherwise element from the second array should be entered to the main array
  56. */
  57. if (arr1[i] < arr2[j]) {
  58. arr[k++] = arr1[i++];
  59. } else {
  60. arr[k++] = arr2[j++];
  61. }
  62. }
  63.  
  64. // If any elements remaining in the first array then those should also be inserted in the main array
  65. while (i != m) {
  66. arr[k++] = arr1[i++];
  67. }
  68.  
  69. // If any elements remaining in the second array then those should also be inserted in the main array
  70. while (j != n) {
  71. arr[k++] = arr2[j++];
  72. }
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement