Using the System class introduced in our lab session and the bubble sort program
ID: 3586310 • Letter: U
Question
Using the System class introduced in our lab session and the bubble sort program discussed in our lecture to report the elapsed time when we use bubble sort program to sort n integers, where n is an integral number input by the user of your program and each integer is between 0 and 99999 inclusive. The following is a sample run of your program.
Input a number (at least 1000):
7000
Bubble sort needs 310 milliseconds to sort 7000 integers.
Continue ? (Yes/No) Yes
Input a number (at least 1000):
60000
Bubble sort needs 25066 milliseconds to sort 60000 integers.
Continue ? (Yes/No) No
Explanation / Answer
// I've uploaded the source code at Gist => https://gist.github.com/anonymous/a50b506fd0e2d721d451b68b51b14b91
import java.util.Scanner;
public class SortTime {
/**
* Sorts and returns an array using bubble sort.
* arr - array to be sorted
*/
private static int[] bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (arr[j - 1] > arr[j]) {
//swap elements
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
public static void main(String[] args) {
int n, i;
String continueProgram;
long startTime, endTime;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Input a number (at least 1000)");
n = sc.nextInt();
if (n<=0 || n>=99999) {
System.out.println("Number must be between 0 to 99999");
continue;
}
int arr[] = new int[n];
for (i=1; i<=n; i++) {
arr[i-1] = i;
}
// Calculate time in ms
startTime = System.currentTimeMillis();
bubbleSort(arr);
endTime = System.currentTimeMillis();
System.out.println("Bubble sort needs " + (endTime - startTime) + " milliseconds to sort " + n + " integers");
System.out.println("Continue ? (Yes/No) ");
sc.nextLine(); // To skip new line after entering number
continueProgram = sc.nextLine();
if (continueProgram.toLowerCase().equals("yes")) {
continue;
} else {
break;
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.