/*
 ============================================================================
 Name        : PointerArithmetic.c
 Author      : Matt Boutell, David Mutchler and YOUR-NAME-HERE
 Description : An exercise to introduce pointer arithmetic.
 ============================================================================
 */

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

#include "PointerArithmetic.h"

int main(void) {
	// Declare a dynamic array of floats, along with other variables as needed.
	float* arr;
	int arrayLength;

	while (1) { // Run until user enters a negative number for the array size.

		arrayLength = getArrayLengthFromUser1();

		if (arrayLength < 0) {
			return EXIT_SUCCESS;
		}

		arr = constructArray(arrayLength);
		fillArrayWithRandomNumbers(arr, arrayLength);

		selectionSort(arr, arrayLength);

		printArray(arr, arrayLength);
		destructArray(arr);
	}
}

// Asks the user for the length of the array and returns the response.
// Does NOT do any error-checking for valid input.
int getArrayLengthFromUser1() {
	int arrayLength;

	printf("Enter length of array: ");
	fflush(stdout);
	scanf("%d", &arrayLength);

	return arrayLength;
}

// Constructs an array of floats with the requested length
// and returns a pointer to the allocated space.
float* constructArray(int arrayLength) {
	return (float*) malloc(arrayLength * sizeof(float));
}

// Fills the array with random numbers between 0 and 1.
void fillArrayWithRandomNumbers(float arr[], int arrayLength) {
	int k;

	for (k = 0; k < arrayLength; ++k) {
		arr[k] = (float) rand() / (float) RAND_MAX;
	}
}

// Sorts the given array.
void selectionSort(float arr[], int arrayLength) {
	int j;
	int k;
	int minJ;
	float temp;

	for (j = 0; j < arrayLength - 1; ++j) {
		minJ = j;
		for (k = j + 1; k < arrayLength; ++k) {
			if (arr[k] < arr[minJ]) {
				minJ = k;
			}
		}
		temp = arr[j];
		arr[j] = arr[minJ];
		arr[minJ] = temp;
	}
}

// Prints the elements of the array, each on a line by itself.
void printArray(float arr[], int arrayLength) {
	int k;

	for (k = 0; k < arrayLength; ++k) {
		printf("%f\n", arr[k]);
	}
	fflush(stdout);
}

// Deallocates memory that was allocated for this array.
void destructArray(float arr[]) {
	free(arr);
}