The problem Write a program that randomly generates an array of 100,000 integers and a key. Estimate the execution time of invoking the linearSearch method. Sort the array and estimate the execution time of invoking the binarySearch method . You can use the following code template to obtain the execution time:
long startTime = System.currentTimeMillis();
perform the task;
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
Breaking it down static final int SAMPLE_SIZE = 100000 ;
public static void main ( String [] args ) {
int valueToSearch = ( int ) ( Math . random () * SAMPLE_SIZE );
Random random = new Random ( 10 );
int [] numbers = random . ints ( 0 , 10 ). limit ( SAMPLE_SIZE ). toArray ();
System . out . println ( "Started linear search..." );
long start = System . currentTimeMillis ();
int index = linearSearch ( numbers , valueToSearch );
long finalTime = System . currentTimeMillis () - start ;
System . out . println ( "Finished linear search." );
System . out . println ( "LinearSearch took: " + finalTime + " index = "
+ index );
System . out . println ( "Sorting array..." );
start = System . currentTimeMillis ();
Arrays . stream ( numbers ). sorted ();
finalTime = System . currentTimeMillis () - start ;
System . out . println ( "Finished sorting." );
System . out . println ( "Sorting took : " + finalTime );
System . out . println ( "Performing binary search..." );
start = System . currentTimeMillis ();
int index2 = Arrays . binarySearch ( numbers , valueToSearch );
System . out . println ( "Finished binary search..." );
finalTime = System . currentTimeMillis () - start ;
System . out . println ( "Binary search took: " + finalTime + " index = "
+ index2 );
}
public static int linearSearch ( int [] numbers , int key ) {
for ( int i = 0 ; i < numbers . length ; i ++) {
if ( numbers [ i ] == key )
return i ;
}
return - 1 ;
}
Output Started linear search...
Finished linear search.
LinearSearch took: 1 index = -1
Sorting array...
Finished sorting.
Sorting took : 1
Performing binary search...
Finished binary search...
Binary search took: 0 index = -100001
Execution time linearSearch sort posted by Justin Musgrove on 24 April 2016
Tagged: java, java-exercises-beginner, intro-to-java-10th-edition, and ch7
Share on: Facebook Google+