Advertisement
bbbbas

MergeSort.java

May 11th, 2014
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. package pr3;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class MergeSort {
  6.  
  7. /**
  8. * Merges two arrays into one.
  9. *
  10. * @param A
  11. * array that contains the two arrays.
  12. * @param temp
  13. * temporary array that we will work with
  14. * @param lo
  15. * lowest index value in the array
  16. * @param mid
  17. * middle index value in the array (represents break between low
  18. * and high values)
  19. * @param hi
  20. * highest index value in the array
  21. */
  22. private static void Merge(int[] A, int[] temp, int lo, int mid, int hi) {
  23. int i = lo;
  24. int j = mid;
  25.  
  26. for (int k = lo; k < hi; k++) {
  27. if (i == mid)
  28. temp[k] = A[j++]; // if lo-mid array is empty
  29. else if (j == hi)
  30. temp[k] = A[i++]; // if mid-hi array is empty
  31. else if (A[j] > A[i])
  32. temp[k] = A[i++]; // i is lower so we put it in the array first
  33. else
  34. temp[k] = A[j++]; // j is lower or equal to i, so we put it in
  35. // the array first.
  36. }
  37.  
  38. // now we need to copy back temp array to its place in A array
  39. for (int k = lo; k < hi; k++)
  40. A[k] = temp[k]; // we are copying only the numbers we just merged.
  41.  
  42. }
  43.  
  44. private static void mergesort(int[] A, int lo, int hi) {
  45. if (hi - lo == 1)
  46. return; // only one element in the array, return.
  47. int mid = lo + (hi - lo) / 2; // find middle
  48. mergesort(A, lo, mid); // sort first part
  49. mergesort(A, mid, hi); // sort second part
  50. Merge(A, new int[A.length], lo, mid, hi); // merge both parts
  51. }
  52.  
  53. /**
  54. * Sorts the given list. (Not in place) Worst Case Performance O(nlogn) Best
  55. * Case Performance O(nlogn) Average Case Performance O(nlogn)
  56. *
  57. * @param A
  58. * list of int array.
  59. */
  60. public static void sortNumbers(int[] A) {
  61. mergesort(A, 0, A.length);
  62. System.out.println(" " + Arrays.toString(A));
  63. }
  64.  
  65. /**
  66. * Just for testing purposes.
  67. */
  68. public static void main(String[] args) {
  69. int[] list = { 156, 344, 54, 546, 767, 23, 34, 64, 234, 654, 234, 65,
  70. 234, 65, 87, 3, 5, 76, 24, 2, 3, 7, 9, 5, 34, 32, 4525, 345, 0 };
  71. sortNumbers(list);
  72.  
  73. }
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement