Monday, October 18, 2010

Assignment 12 - Selection Sort Test




/*
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 slection 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 in two elements

public void swap( int first, int second )
{
int temporary = data[first]; // store first in temporary
data[first] = data[second]; // replace first with second
data[second] = temporary; // put temporary in second
}

//print a pass of algorigthm

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

//output elements till selectem item

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.println("\n"); //add endline
}

//method to output balues 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 perform selection sort

SelectionSort sortArray = new SelectionSort(10);

System.out.println( "Unsorted 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