Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Assignment4;
- import java.util.Arrays;
- public class TestMergeSort
- {
- public static void main (String args[])
- {
- String[] names = {"Lisa", "Adam", "John", "Vicky", "George", "Beth", "Kate", "Aaron", "Jinny"};
- mergeSort(names);
- for (String s :names)
- {
- System.out.println(s);
- }
- }
- /**
- * This function recursively splits the original array into halves until each node is 1 entry.
- * @param names a array of type string
- */
- public static void mergeSort (String[] names)
- {
- if (names.length >= 2)//Breaks array into pairs
- {
- String[] a = new String[names.length/2]; //Makes an array half the size of the original
- String[] b = new String[names.length - names.length/2];//Makes an array for the rest of the size of the original
- for (int i=0; i<a.length;i++)
- {
- a[i]=names[i];//Puts half the original array into a temp array
- }
- for (int i=0; i<b.length; i++)
- {
- b[i] = names[i + names.length /2];//Puts the other half of the array into a temp array
- }
- mergeSort(a);
- mergeSort(b);
- merge(names, a, b);
- }
- }
- /**
- * This function takes the nodes then merges them in order
- * @param names An array of type string
- * @param a An array of type string
- * @param b An array of type string
- */
- public static void merge (String[] names, String[] a, String[] b)
- {
- int count1=0;
- int count2=0;
- System.out.println("Pre loop names is: " + Arrays.toString(names));
- for (int i=0; i<names.length; i++)
- {
- if (count2>= b.length || count1<a.length && a[count1].compareToIgnoreCase(b[count2]) < 0)//ensures array does not go out of bounds, and sorts array
- {
- names[i]=a[count1];
- count1++;
- }
- else
- {
- names[i]=b[count2];
- count2++;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement