Question: Using the System class introduced in our lab session and the insertion sort program discussed in our lecture to report the elapsed time when we
Using the System class introduced in our lab session and the insertion sort program discussed in our lecture to report the elapsed time when we use insertion 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): 3000 Insertion sort needs 20 milliseconds to sort 3000 integers. Continue ? (Yes/No) Yes Input a number (at least 1000): 20000 Insertion sort needs 611 milliseconds to sort 20000 integers. Continue ? (Yes/No) No. Please answer this question, using those codes. Thank you!
class TestInsertion
{
public static void main(String[] args)
{
int n = 10;
int[] myarray = new int[n];
for (int i = 0; i < myarray.length; i++)
myarray[i] = (int) (Math.random()*100);
System.out.println(myarray.length + " numbers are generated and they are");
for (int i = 0; i < myarray.length; i++)
System.out.print(myarray[i] + " ");
System.out.println();
System.out.println();
insertionSort(myarray);
System.out.println(myarray.length + " numbers are sorted and they are");
for (int i = 0; i < myarray.length; i++)
System.out.print(myarray[i] + " ");
}
public static void insertionSort(int[] array)
{
for (int i = 1; i < array.length; i++)
{
int itemToInsert = array[i];
int j = i - 1;
while (j >= 0)
{
if (itemToInsert < array[j])
{
array[j+1] = array[j];
j--;
}
else break;
}
array[j+1] = itemToInsert;
}
}
}
import javax.swing.*;
public class Example {
public static void main(String[] args) {
String size;
int s;
size = JOptionPane.showInputDialog("Input size of array" + " >= 5000");
s = Integer.parseInt(size);
int[] Array = new int[s];
for (int i = 0; i < Array.length; i++) { Array[i] = 100*i + 29; }
int total = 0;
long startTime = System.currentTimeMillis(); for (int i = 0; i < Array.length; i++) { total = total + Array[i]; } long stopTime = System.currentTimeMillis();
System.out.println("The execution time is: " + (stopTime - startTime) + " milliseconds"); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
