public class SortedChecker extends Thread
{
	private static int[] array;

	private int lower;
	private int upper;
	
	private boolean sortedOk;
	public  boolean sortedOk () {return sortedOk;}
	
	private boolean sorted;
	public    boolean sorted () {return sorted;}
	
	public SortedChecker (int lower, int upper)
	{
		assert array != null        : "precondition";
		assert 0 <= lower           : "precondition";
		assert lower <= upper       : "precondition";
		assert upper < array.length : "precondition";
		this.lower = lower;
		this.upper = upper;
	}
        
	public void run ()
	{
		System.out.println(lower + ".." + upper);
		if (lower + 1 >= upper)
		{
			sortedOk = true;
			sorted = array[lower] <= array[upper];
		}
		else
		{
			int mid = (lower + upper) / 2;
			SortedChecker left  = new SortedChecker(lower, mid);
			SortedChecker right = new SortedChecker(mid, upper);
			left.start();
			right.start();
			try
			{
				left.join();
				right.join();
				sortedOk = left.sortedOk() && right.sortedOk();
				sorted = left.sorted() && right.sorted();
			}
			catch(InterruptedException e)
			{
				System.out.println
					("InterruptedException caught when joining left or right subthread! -- "
					 + e.toString());
			}
		}
	}
	
	private static void checkSorted ()
	{
		SortedChecker first = new SortedChecker(0 , array.length - 1);
		first.start();
		try
		{
			first.join();
		}
		catch(InterruptedException e)
		{
			System.out.println
				("InterruptedException caught when joining first subthread! -- "
				 + e.toString());
		}
		if (first.sortedOk())
		{
			System.out.println
				("The array is " + (first.sorted() ? "" : "not ") + "sorted.");
		}
		else
		{
			System.out.println("Something went wrong. The array could not be checked.");
		}
	}
	
	public static void main (String[] args)
	{
		int arraySize = 1;
		try
		{
			if (args.length > 0)
			{
				arraySize = Math.max(Integer.parseInt(args[0]),arraySize);
			}
		}
		catch(NumberFormatException e)
		{
			System.out.println
				("If 1 argument, then integer >= 1 expected! --- " + e.toString());
		}
		array = new int[arraySize];
		
		System.out.println("First array should not be sorted.");
		for (int i = 0; i < array.length; i++)
		{
			array[i] = (new Double(Math.random() * arraySize)).intValue();
		}
		checkSorted();
		
		System.out.println("Second array should be sorted.");
		array[0] = (new Double(Math.random())).intValue();
		for (int i = 1; i < array.length; i++)
		{
			array[i] = array[i - 1] + (new Double(Math.random())).intValue();
		}
		checkSorted();
	}
}