import java.util.Arrays;

public class SelectionSort {

	public static final int ARRAY_SIZE = 100000;
	public static final int MAX_VALUE = 10*ARRAY_SIZE;
	
	public static void main(String[] args) {
		
		
		int[] test = {7, 2, 9, 3, 0, 1, 5, 8, 3};
		swap(test, 1, 5);
		System.out.println(Arrays.toString(test));
		selectionSort(test);
		System.out.println(Arrays.toString(test));
		
		
		//time test
		int[] data = generateData();
		
		
		//get the time from the computer
		long t1 = System.currentTimeMillis();
		
		selectionSort(data);
		//Arrays.sort(data);

		//get the time when done
		long t2 = System.currentTimeMillis();
		
		//time in seconds
		double sec = (t2-t1)/1000.0;
		
		System.out.printf("Sort time %f seconds.\n", sec);
		
		if(isSorted(data)) {
			System.out.println("Sort successful.");
		}
		else {

			System.out.println("Sort failed.");
		}
		
		

	}
	
	//create an array of random integers.
	//return: a new array of random integers
	public static int[] generateData(){
		int[] result = new int[ARRAY_SIZE];
		
		for(int i = 0; i < result.length; i++){
			result[i] = (int)(MAX_VALUE*Math.random());
		}
		return result;
	}
	
	//selectionSort
	//sort the array in ascending order (in place)
	//parameters:
	//  data: an array of integers
	public static void selectionSort(int[] data){
		//for each item in the array (not including the last)
		//  find the index of the minimum
		//  swap it into place
		for(int i = 0; i < data.length - 1; i++) {
			int minIndex = findMinimumIndex(data, i);
			if(minIndex != i) {
				swap(data, i, minIndex);
			}
		}
	}
	
	//swap two values in the array
	//parameters
	//  data: the array of integers 
	//  a, b: the indices of the values to swap
	public static void swap(int[] data, int a, int b){
		//swap the values at locations a nd b
		int temp = data[a];
		data[a] = data[b];
		data[b] = temp;
	}
	
	//isSorted
	//determine if the array of integers is sorted.
	//parameters:
	//  data: an array of integers
	// return: true if the array is in ascending order, false otherwise
	
	public static boolean isSorted(int[] data) {
		for(int i = 1; i < data.length; i++) {
			//check if this is < the previous
			if(data[i] < data[i-1]) {
				//out of order!
				return false;
			}
		}
		return true;
	}
	
	
	//find the index of the minimum value in the array
	//parameter
	//  data: the array of integers to search
	//  start: the index to start the search
	//return: index of the minimum value
	public static int findMinimumIndex(int[] data, int start){
		//keep track of the smallest (location)
		int index = start;
		
		for(int i = start + 1; i < data.length; i++){
			//check if this one is smaller
			if(data[i] < data[index]){
				//remember the location of the new smallest
				index = i;
			}
		}
		return index;
	}
	
	

}
