/*
Lauren Cairco Dukes
CPSC 1110
Selection sort example, demonstrated with a function
*/
#include <stdio.h>

void selectionsort(int x[], int length);

int main(void){
	//declare two arrays
	int x[5] = {5, 3, 2, 1, 4};
	int y[10] = {10, 9, 7, 6, 4, 1, 2, 5, 3, 8};

	//sort and print the first one
	selectionsort(x,5);

	printf("x sorted: \n");
	int i = 0;
	for (i = 0; i < 5; i++){
		printf("%d\n",x[i]);
	}

	//sort and print the second one
	selectionsort(y,10);

	printf("y sorted: \n");
	for (i = 0; i < 10; i++){
		printf("%d\n",y[i]);
	}

	

	return 0;
}

//selection sort
/*
Sorts the array given as a parameter to the function using the
selection sort algorithm.
Parameters:
int x[] -- array of integers that are to be sorted
int length -- number of items that are in the array
*/
void selectionsort(int x[], int length){
	int i = 0;
	int j = 0;
	int smallestIndex = 0;
	//go through the array, starting at the first spot
	for (i = 0; i < length; i++){
		//assume that the smallest number is at the ith spot
		smallestIndex = i;

		//go through the entire array below the ith position
		for (j = i; j < length; j++){
			//if we find an item that's smaller than the current item where we've seen
			//the smallest so far
			if (x[j] < x[smallestIndex]){
				//set smallestIndex to that index
				smallestIndex = j;
			}
		}

		//now that we found the smallest in the rest of the array, swap it
		//with the i position, so it's at the top of the array
		int swap = x[i];
		x[i] = x[smallestIndex];
		x[smallestIndex] = swap;

		//at this point, positions 0 through i are now sorted
	}
}
