Sunday, December 19, 2010

Assignment 12 - SelectionSort / Test

Assignment 12 - SelectionSort / Test and Image Result

/*

//Selection Sort Algorithm
*/

import java.util.Random;

public class SelectionSort
{
private int[] data; //array of value
private static Random generator = new Random();

//create array if given size and fill w/ random int
public  SelectionSort( int size)
{
data = new int[size]; //create space for array

//fill array with random int 10-99
for( int i = 0; i < size; i++ )
data[i] = 10 + generator.nextInt( 90 );
}

//sort array using selection sort
public void sort()
{
int smallest; //index of smallest element

//loop over data length -1
for (int i = 0; i < data.length - 1; i++)
{
smallest = i; //first index of remaining array

//loops to find index of smallest element
for (int index = i + 1; index < data.length; index++)
if( data[index] < data[smallest])
smallest = index;

swap( i, smallest); //swap smallest elements into position
printPass( i + 1, smallest );
}
}

//helper method to swap values intwo elements
public void swap( int first, int second )
{
int temporary = data[first]; //store first in temporary
data[first] = data[second]; //replace first in second
data[second] = temporary; // put temporary in second
}

//print a pass of algorithm
public void printPass( int pass, int index )
{
System.out.print( String.format( "after pass %2d: ",pass) );

//output elements till selected itme
for (int i=0; i < index; i++)
System.out.print( data[i] + " ");

System.out.print( "\n      "); //for alignment

//indicate amount of array that is sorted
for( int j = 0; j < pass; j++ )
System.out.print("--");
System.out.println("\n"); //add endline
}

//method to output values in array
public String toString()
{
StringBuilder temporary = new StringBuilder();

//iterate through array
for (int element : data)
temporary.append( element + " " );

temporary.append("\n");
return temporary.toString();
}
}














/*

//main function
*/

public class SelectionSortTest
{
public static void main( String[] args )
{
//create object to preform selection sort
SelectionSort sortArray = new SelectionSort(10);

System.out.println( "Unsortoed array:");
System.out.println( sortArray ); //print unsorted array

sortArray.sort(); //sort array

System.out.println( "Sorted Array:");
System.out.println( sortArray ); //print sorted array
}
}

No comments:

Post a Comment