/* This program uses code from "Algorithms in C, Third Edition,"
 *               by Robert Sedgewick, Addison-Wesley, 1998.
 */

#include <stdlib.h>
#include <stdio.h>

#include "list_interface.h"

/* this is the version of insertionSort where all insertions are 
 * done calling insertLink, including cases where the insertion
 * happens at the beginning of the list */
list insertionSort_old(list numbers)
{
   list result = newList();
   link source;
   for (source = listFirst(numbers); source != NULL; source = linkNext(source))
   {
      int value = linkItem(source);
      link new_link = newLink(value);
      link current = 0;
      link next = listFirst(result);
      while((next != NULL) && (value > linkItem(next)))
      {
         current = next;
         next = linkNext(next);
      }
      insertLink(result, current, new_link);
   }
   
   return result;
}


/* this is the version of insertionSort where insertions at the 
 * beginning of the list are handled using function insertAtBeginning*/
list insertionSort(list numbers)
{
   list result = newList();
   link source;
   for (source = listFirst(numbers); source != NULL; source = linkNext(source))
   {
      int value = linkItem(source);
      link new_link = newLink(value);
      link first = listFirst(result);
      
      /* check if we need to insert at the beginning */
      if ((first == NULL) || (value < linkItem(first)))
      {
         insertAtBeginning(result, new_link);
      }
      else
      {
         link current = first;
         link next = linkNext(first);
         while((next != NULL) && (value > linkItem(next)))
         {
            current = next;
            next = linkNext(next);
         }
         insertLink(result, current, new_link);
      }
   }
   
   return result;
}


list randomIntegers(int size, int limit)
{
   list result = newList();
   link current = listFirst(result);
   int i;
   for (i = 0; i < size; i++)
   {
      int value = rand() % limit;
      link new_item = newLink(value);
      insertLink(result, current, new_item);
      current = new_item;
   }
   
   return result;
}

main()
{
   srand(time(NULL));

   list numbers = randomIntegers(10, 1000);
   printf("printing original list:");
   printList(numbers);
   
   list sorted_numbers = insertionSort(numbers);
   printf("printing result (ascending order):");
   printList(sorted_numbers);

   reverse(sorted_numbers);   
   printf("printing result (ascending order):");
   printList(sorted_numbers);
   
   destroyList(numbers);
   destroyList(sorted_numbers);
   
   return 0;
}
