Advertisement
Guest User

Untitled

a guest
Mar 20th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. package Assignment4;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class TestMergeSort
  6. {
  7.  
  8.  
  9. public static void main (String args[])
  10. {
  11. String[] names = {"Lisa", "Adam", "John", "Vicky", "George", "Beth", "Kate", "Aaron", "Jinny"};
  12. mergeSort(names);
  13. for (String s :names)
  14. {
  15. System.out.println(s);
  16. }
  17. }
  18. /**
  19. * This function recursively splits the original array into halves until each node is 1 entry.
  20. * @param names a array of type string
  21. */
  22. public static void mergeSort (String[] names)
  23. {
  24. if (names.length >= 2)//Breaks array into pairs
  25. {
  26. String[] a = new String[names.length/2]; //Makes an array half the size of the original
  27. String[] b = new String[names.length - names.length/2];//Makes an array for the rest of the size of the original
  28. for (int i=0; i<a.length;i++)
  29. {
  30. a[i]=names[i];//Puts half the original array into a temp array
  31. }
  32. for (int i=0; i<b.length; i++)
  33. {
  34. b[i] = names[i + names.length /2];//Puts the other half of the array into a temp array
  35. }
  36. mergeSort(a);
  37. mergeSort(b);
  38. merge(names, a, b);
  39. }
  40. }
  41. /**
  42. * This function takes the nodes then merges them in order
  43. * @param names An array of type string
  44. * @param a An array of type string
  45. * @param b An array of type string
  46. */
  47. public static void merge (String[] names, String[] a, String[] b)
  48. {
  49. int count1=0;
  50. int count2=0;
  51. System.out.println("Pre loop names is: " + Arrays.toString(names));
  52.  
  53. for (int i=0; i<names.length; i++)
  54. {
  55.  
  56. if (count2>= b.length || count1<a.length && a[count1].compareToIgnoreCase(b[count2]) < 0)//ensures array does not go out of bounds, and sorts array
  57. {
  58. names[i]=a[count1];
  59. count1++;
  60. }
  61. else
  62. {
  63. names[i]=b[count2];
  64. count2++;
  65. }
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement