/*
 * @(#)MergeSortAlgorithm.java	1.0 95/06/23 Jason Harrison
 *
 * Copyright (c) 1995 University of British Columbia
 *
 * Permission to use, copy, modify, and distribute this software
 * and its documentation for NON-COMMERCIAL purposes and without
 * fee is hereby granted provided that this copyright notice
 * appears in all copies. Please refer to the file "copyright.html"
 * for further important copyright and licensing information.
 *
 * UBC MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. UBC SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

/**
 * A merge sort demonstration algorithm
 * SortAlgorithm.java, Thu Oct 27 10:32:35 1994
 *
 * @author Jason Harrison@cs.ubc.ca
 * @version 	1.1, 12 Jan 1998
 *   
 * 27 Nov 2006: (bwbecker@uwaterloo.ca) Changed the overall architecture to
 * use model-view-controller.  Re-examined algorithm to ensure that counting
 * was consistent across all algorithms (the quicksorts used to ignore most
 * of the comparisons in the partitioning, for example).
 */
class MergeSortAlgorithm extends SortAlgorithm
{
	void sort(int a[], int lo0, int hi0)
	{
		int lo = lo0;
		int hi = hi0;
		super.updateAllViews(lo, hi);

		if (lo >= hi)
		{
			return;
		}
		int mid = (lo + hi) / 2;

		/*
		 *  Partition the list into two lists and sort them recursively
		 */
		sort(a, lo, mid);
		sort(a, mid + 1, hi);

		/*
		 *  Merge the two sorted lists
		 */
		int end_lo = mid;
		int start_hi = mid + 1;
		super.lowMarker = lo0;
		super.hiMarker = hi0;
		
		while ((lo <= end_lo) && (start_hi <= hi))
		{
			
			//pause(lo);
			if (stopRequested)
			{
				return;
			}
			super.compares++;
			if (a[lo] < a[start_hi])
			{
				lo++;
			} else
			{
				/*  
				 *  a[lo] >= a[start_hi]
				 *  The next element comes from the second list, 
				 *  move the a[start_hi] element into the next 
				 *  position and shuffle all the other elements up.
				 */
				super.other++;
				int T = a[start_hi];
				for (int k = start_hi - 1; k >= lo; k--)
				{
					a[k + 1] = a[k];
					super.moves++;
					super.activeMarker = k;
					super.updateAllViews();
				}
				a[lo] = T;
				super.other++;
				lo++;
				end_lo++;
				start_hi++;
			}
		}
	}

	void sort(int a[])
	{
		sort(a, 0, a.length - 1);
		super.updateAllViews(-1, -1);
	}
}
