Another simple program that places a timer on the bubble sort, ill compare this to other sorts at later date.
-------------------------- CODE -------------------------------------------
import java.util.Random;
class bubble
{
public static void main(String args[])
{
int[] number = new int[20000]; //CREATE LARGE INTEGER ARRAY
Random rand = new Random(); //CREATE INSTANCE OF RANDOM CLASS
int buffer; // NEED THIS TEMPORARY STORE PLACE FOR THE BUBBLE SORT
long HLong; // TIMER VARIABLE
//BUILD ARRAY OF RANDOM NUMBERS
for(int x=0; x<number.length; x++)
number[x]=rand.nextInt(999);
//START TIMER BY PLACING TIME IN TO VARIABLE
HLong=DoTimingStart();
// DO THE BUBBLE SORT
for(int y=0; y<number.length; y++) // START OUTER LOOP
{
for(int z=0; z<(number.length-1); z++) // START INNER LOOP
{
if(number[z+1] > number[z]) // CHECK IF POSITION Z+1 IS LARGER THAN Z
{
buffer = number[z+1]; // COPY POSITION Z + 1 TO BUFFER VARIABLE
number[z+1]=number[z]; //COPY POSITION Z TO POSITION Z+1
number[z]=buffer; // COPY BUFFER TO POSITION Z
}
}
}
//STOP TIMER BY SUBTRACTING START TIME BY PRESENT TIME
HLong= (DoTimingEnd()-HLong);
System.out.println("Length Time : "+HLong);
}
//USE 2 METHODS FOR DEMONSTRATION PURPOSES - ONE SHOULD BE USED
private static long DoTimingStart()
{
long start = System.currentTimeMillis();
return start;
}
private static long DoTimingEnd()
{
long end = System.currentTimeMillis();
return end;
}
}
-----------------------------OUTPUT----------------------------------------
Length Time : 1828
No comments:
Post a Comment