/**
 * Test bed for your sort functions from TP3.
 * Instructions:
 *   . Create your own sort function, with the following prototype:
 *         void my_sort_function(int array_size, int array[]);
 *   . Compile it with the following command:
 *         gcc -W -Wall -Wextra -o sort_testbed sort_testbed.c
 *   . Run it in one of the following two modes:
 *         ./sort_testbed <array size>
 *         ./sort_testbed <array size> <seed> (different random arrays)
 */

#include <stdio.h>
#include <stdlib.h>

/**
 * A test comparator based on the existing quicksort implementation in C.
 * The first method is a comparator for integers; the second actually implements
 * quick sort using qsort().
 */
int my_int_comparator(const void* a, const void* b) {
  return *((const int*) a) - *((const int*) b);
}

void my_sort_function(int array_size, int array[]) {
  qsort(array, array_size, sizeof(int), &my_int_comparator);
}

/* Prints the @p array, using @p header as a descriptor. */
void print_array(const char* header, int array_size, const int array[]) {
  int i;
  printf("%sint array[%d]: ", header, array_size);
  for (i = 0; i < array_size; ++i) {
    printf("%d ", array[i]);
  }
  printf("\n");
}

/* Checks that the @p array is actually sorted; if not, displays a warning. */
void check_array_order(int array_size, const int array[]) {
  int i;
  for (i = 1; i < array_size; ++i) {
    if (array[i] < array[i-1]) {
      printf("The array is not in sorted: (array[%d]: %d) < (array[%d]: %d)\n",
             i, array[i], i-1, array[i-1]);
      return;
    }
  }
}

int main(int argc, char** argv) {
  int array_size = 0;
  int* array = NULL;
  int i;

  /* Print the program usage string. */
  if (argc < 2) {
    printf("Usage: %s <array_size> [<seed>]\n", argv[0]);
    return 1;
  }

  /* Determine the test array size, and prepare the random generator seed.
   * Unless the seed is passed as an argument, it is set to the array size, so
   * that the same random sequence will be used across runs. */
  array_size = atoi(argv[1]);
  srand(argc > 2 ? atoi(argv[2]) : array_size);
  if (array_size < 1) {
    printf("The array size must be a positive integer.\n");
    return 2;
  }

  /* Prepare a random table to sort, with elements between 0 and 10,000. */
  array = (int*) calloc(array_size, sizeof(int));
  for (i = 0; i < array_size; ++i) {
    array[i] = rand() % 10000;
  }

  /* Print the array before sorting. */
  print_array("Before: ", array_size, array);

  /* Execute the sort algorithm. REPLACE WITH YOUR OWN METHOD HERE. */
  my_sort_function(array_size, array);

  /* Check that the array is actually sorted, and clean up the heap. */
  check_array_order(array_size, array);
  print_array("After: ", array_size, array);
  free(array);

  return 0;
}
