/* sortDemo.c  */


#include <stdio.h>


int positionOfLargest(int a[], int size)
{

  int position = 0;

  int i;

  for (i=1; i<size; i++)
    {
      if (a[i] > a[position])
	position = i;

    }
  
  return position;

}

void swap ( int *a, int *b)
{
  int temp;
  temp = (*a);
  (*a) = (*b);
  (*b) = temp;
  
}

void sort(int a[], int size)
{
  int i;

  int wheresTheLargest;

  for (i=size; i > 1; i--   )
    {
      /* each time through loop, find the
	 largest in the first i elements.

	 First time, its the entire array,
	 each time through the part that
	 remains unsorted gets smaller and smaller */

      wheresTheLargest = positionOfLargest(a, i);
      swap(&a[wheresTheLargest], &a[i-1]); 

      /* 
	 We could write this as one line of code:

	 swap(&a[positionOfLargest(a,i)], &a[i-1]);

	 But that is being too "annoyingly clever"

      */


    }

}

void printArray( int a[], int size, char *name)
{
  int i;

  for (i=0; i<size; i++)
    {
      printf("%s[%d] = %d\n", name, i, a[i]);
    }
  
}

int main(void)
{

  int someNums[] = { 6, 9, 12, 7, 16, 8, 2};

  int size = 7;
  
  printf("---not sorted---\n");
  printArray(someNums, size, "someNums");

  sort(someNums, size);

  printf("---sorted---\n");
  printArray(someNums, size, "someNums");

  
  return 0;

}




