hello, i need some help with the following question. ... Write a java program th
ID: 3681250 • Letter: H
Question
hello, i need some help with the following question. ...
Write a java program that prompts the user for two numbers, n for the number of items in the array to sort, and num_i for a number of iterations. Then do the following:
Initiate a variable running_time to 0
Create a for loop that iterates num_i times.
In the body of the loop, Create an array of n random integers
Get the time and set this to start-time.
You will have to figure out what the appropriate command is in the programming language you are using to find them time Use bubble sort to sort the array
Get the time and set this to end-time
Subtract end-time from start-time and add the result to running_time
Once the program has run, note The number of items sorted The number of iterations The average running time for each size array Repeat the process nine times, using 50, 250 and 500 as the size of the array, and 100, 1000 and 10,000 as the number of iterations.
Explanation / Answer
package assignment;
import java.util.Calendar;
import java.util.Random;
import java.util.Scanner;
public class BubbleSortNiterations {
public static void main(String args[]) {
int n = 0;
int num_i = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of items");
n = sc.nextInt();
System.out.println("Enter number of iterations");
num_i = sc.nextInt();
long running_time = 0;
long start = 0;
long end = 0;
Random rand = new Random();
int numbers[] = new int[n];
for (int i = 0; i < num_i; i++) {
start = 0;
end = 0;
for (int j = 0; j < n; j++)
numbers[j] = rand.nextInt();
start = Calendar.getInstance().getTimeInMillis();
bubbleSort(numbers);
end = Calendar.getInstance().getTimeInMillis();
running_time += end - start;
}
System.out.println("No of items# "+n+" No of iterations# "+num_i+" Avg running time# "+ (float)(running_time)/num_i);
}
private static void bubbleSort(int[] intArray) {
int n = intArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (intArray[j - 1] > intArray[j]) {
// swap the elements
temp = intArray[j - 1];
intArray[j - 1] = intArray[j];
intArray[j] = temp;
}
}
}
}
}
--outpput-------------------
Enter number of items
50
Enter number of iterations
100
No of items# 50 No of iterations# 100 Avg running time# 0.31
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.