#include <stdio.h>
#define SIZE 9
/**
 * Terry Harvey CIS 105 Section 010 TA Tina Weymouth
 *  Demonstration program for recursive selection sort
 *
 * Note that a sorting function is only possible because arrays are
 * passed by reference, so that the array in the calling function gets
 * changed.
 **/
void printArray(int data[], int size);
int findMaxIndex(int numbers[], int size);
void swapTwoValues(int data[], int index1, int index2);
void selectionSort(int data[], int size);

int main(){
    int length[] = {12,5,9,1,8,7,40,14,0};

    printf("%d\n", findMaxIndex(length, SIZE));

    printArray(length, SIZE);
    selectionSort(length, SIZE);
    printArray(length, SIZE);

    return 0;
}

void selectionSort(int data[], int size){
    int maxIndex;
    if (size <= 1){ //an array of size one is already sorted
        printf("done!\n");
        return;
    }
    
    printf("array being sorted is now: ");
    printArray(data, size);
    maxIndex = findMaxIndex(data, size);
    swapTwoValues(data, maxIndex, size - 1); //size-1 is index at end of array
    selectionSort(data, size - 1); //sort the rest of the array (hide the end)
}

void swapTwoValues(int data[], int index1, int index2){
    int temp;
    printf("swapping %d and %d\n",data[index1],data[index2]);
    temp = data[index2];
    data[index2] = data[index1];
    data[index1] = temp;
    return;
}

int findMaxIndex(int numbers[], int size){
    int i;
    int maxIndex = 0;
    for(i = 1; i < size; i++)
        if (numbers[i] > numbers[maxIndex])
            maxIndex = i;
    return maxIndex;
}

void printArray(int data[], int size){
    int i;
    for ( i = 0; i < size; i++)
        printf("%d ", data[i]);
    printf("\n");
    return;
}
