Write a program called InsertionSortBenchmark that automatically generates a tab
ID: 3822309 • Letter: W
Question
Write a program called InsertionSortBenchmark that automatically generates a table of sample run times for the insertion sort algorithm. The program should ask for the smallest and largest value of n and the number of measurements and then execute all sample runs. You should plan to have a method (e.g., "public static int[] generateData(int n)") in your program that generates int arrays of a specific length and populates them with random numbers (use Random's nextInt). This will be needed to run the different tests. To time the running algorithm, you will need to use the StopWatch class (see attached). Also attached is InsertionSorter.java, which contains an implementation of insertion sort. The algorithm is available as a static method directly from that file. [10 points] Sample Output (updated on 11/17 to fix missing zeros):
output SER200 HW11 (run) X Please enter the smallest array size (n) to test: 10000 Please enter the largest array size (n) to test: 100000 Please enter the number of measurements to take: 10 Size Time (milliseconds) 10000 15 20000 32 30000 85 40000 160 50000 238 341 60000 472 70000 80000 618 90000 768 100000 947Explanation / Answer
HI, PLease find my implementation.
Please let me know in case of any issue.
import java.util.Random;
import java.util.Scanner;
public class InsertionSortTest {
public static int[] generateData(int n){
Random random = new Random();
int[] arr = new int[n];
for(int i=0; i<n; i++)
arr[i] = random.nextInt(1000); // in range 0-999
return arr;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the smallest array size to test: ");
int low = sc.nextInt();
System.out.print("Please enter the largest array size to test: ");
int high = sc.nextInt();
System.out.print("Please enter the number of measurement to take: ");
int measure = sc.nextInt();
StopWatch watch = new StopWatch();
System.out.println("Size Time (milliseconds)");
for(int i=1; i<=measure; i++){
int n = low*i;
watch.reset();
watch.start();
int []arr = generateData(n);
InsertionSorter.sort(arr);
watch.stop();
System.out.println(n+" "+watch.getElapsedTime());
}
}
}
/*
Sample run:
Please enter the smallest array size to test: 10000
Please enter the largest array size to test: 100000
Please enter the number of measurement to take: 10
Size Time (milliseconds)
10000 41
20000 128
30000 110
40000 188
50000 294
60000 420
70000 591
80000 762
90000 984
100000 1198
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.