package highOrder;

import java.util.Random;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class TestQuicksort extends TestCase {

  public TestQuicksort(String name) {
    super(name);
  }

  public static Test suite(){
    return new TestSuite(TestQuicksort.class);
  }

  public void testSame() throws Exception {
    int a[] = {1, 1, 1, 1, 1, 1, 1, 1};
    Sorter s = new AscendingSorter(a);
    s.sort();
    boolean isSorted = checkSorted(a);
    assertEquals(true, isSorted);
  }

  public void testZero() throws Exception {
    int a[] = new int[0];
    Sorter s = new AscendingSorter(a);
    s.sort();
    boolean isSorted = checkSorted(a);
    assertEquals(true, isSorted);
  }

  public void testSortRandom() throws Exception {
    int a[] = new int[100];
    fillRandomArray(a, -100, 100);
    Sorter s = new AscendingSorter(a);
    s.sort();
    boolean isSorted = checkSorted(a);
    assertEquals(true, isSorted);
  }

  public void testManyRandom() throws Exception {
    int a[] = new int[1048576];
    fillRandomArray(a, -32768, 32767);
    Sorter s = new AscendingSorter(a);
    s.sort();
    boolean isSorted = checkSorted(a);
    assertEquals(true, isSorted);
  }


  public void testSameDown() throws Exception {
    int a[] = {1, 1, 1, 1, 1, 1, 1, 1};
    Sorter s = new DescendingSorter(a);
    s.sort();
    boolean isSorted = checkSortedDown(a);
    assertEquals(true, isSorted);
  }

  public void testZeroDown() throws Exception {
    int a[] = new int[0];
    Sorter s = new DescendingSorter(a);
    s.sort();
    boolean isSorted = checkSortedDown(a);
    assertEquals(true, isSorted);
  }

  public void testSortRandomDown() throws Exception {
    int a[] = new int[100];
    fillRandomArray(a, -100, 100);
    Sorter s = new DescendingSorter(a);
    s.sort();
    boolean isSorted = checkSortedDown(a);
    assertEquals(true, isSorted);
  }

  public void testManyRandomDown() throws Exception {
    int a[] = new int[1048576];
    fillRandomArray(a, -32768, 32767);
    Sorter s = new DescendingSorter(a);
    s.sort();
    boolean isSorted = checkSortedDown(a);
    assertEquals(true, isSorted);
  }
  
  private static boolean checkSorted(int[] a) {
    for (int i = 0; i < a.length - 1; i++) {
      if (a[i] > a[i+1]) {
        return false;
      }
    }
    return true;
  }
  
  private static boolean checkSortedDown(int[] a) {
    for (int i = 0; i < a.length - 1; i++) {
      if (a[i] < a[i+1]) {
        return false;
      }
    }
    return true;
  }

  private static void fillRandomArray(int[] a, int min, int max) {
    Random randomGenerator = new Random();
    int interval = max - min;
    for (int idx = 0; idx < a.length; ++idx) {
      a[idx] = randomGenerator.nextInt(interval) + min;
    }
  }
}
