I’m having trouble printing out a MergeSort. I need help printing out each step by step process as it’s sorting an ArrayList.
The following example is from a InsertionSort, as I had it print at every single time it swapped two elements in the ArrayList:
11 79 60 45 START
11 79 60 45
11 60 79 45
11 45 60 79 FINISH
Is there anyway to do this for MergeSort while showing the entire array from start to finish (like above?)
Code:
import java.util.ArrayList;
public class Merge
{
public static void main (String [] args)
{
Merge run = new Merge();
run.test();
}
public void test ( )
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < 16; i++)
{
numbers.add(new Integer(1 + (int)(Math.random() * 100)));
}
printArray(numbers);
mergeSort(numbers);
printArray(numbers);
}
public void printArray (ArrayList<Integer> array)
{
System.out.println("\n\n");
for (int i = 0; i < array.size(); i++)
{
System.out.printf("%-5d",array.get(i).intValue());
}
System.out.println("\n\n");
}
public void mergeSort (ArrayList<Integer> array)
{
int length = array.size();
if (length < 2)
{
return; // the array is already sorted in this case
}
// divide
ArrayList<Integer> array1 = new ArrayList<Integer>();
ArrayList<Integer> array2 = new ArrayList<Integer>();
int i = 0;
while (i < length/2)
{
array1.add(array.remove(0)); // move the first n/2 elements to array1
i++;
}
while (!array.isEmpty())
{
array2.add(array.remove(0)); // move the rest to array2
}
mergeSort(array1);
mergeSort(array2);
merge(array1,array2,array);
}
public void merge (ArrayList<Integer> array1, ArrayList<Integer> array2, ArrayList<Integer> array)
{
while (!array1.isEmpty() && !array2.isEmpty())
{
if ((array1.get(0).compareTo(array2.get(0)) <= 0))
{
array.add(array1.remove(0));
}
else
{
array.add(array2.remove(0));
}
}
while(!array1.isEmpty()) // move the remaining elements of array1
{
array.add(array1.remove(0));
}
while(!array2.isEmpty()) // move the remaining elements of array2
{
array.add(array2.remove(0));
}
}
}
If you passed some offset to
mergeSort, you may be able to print the sub-array indented over to where it would be in the full array as you make swaps, but since you are only passing portions of the array down, you won’t be able to show the full array in this manner. However, there is a faster way that would allow you to.Instead of making new arrays and passing them down, pass the array and 2 indices, the begin and end point. So you say
mergeSort(array, 0, n)for the first, thenmergeSort(array, 0, n/2)andmergeSort(array, n/2, n)for the recursive calls. You do your splitting and merging only within those bounds. Then as you merge, you can print out the whole merged array. This would show the step at each merge. At the bottom level, it would show the 1-1 swap (if it occurs). That’s the only “step-by-step” you could see in a merge sort.