below is my selection sort method code, I only wrote the main part, but i don\'t
ID: 3870420 • Letter: B
Question
below is my selection sort method code, I only wrote the main part, but i don't how to write part of it. my task is to test 100, 1000, 10000 data sets. and the result should be look like this 0.04951192
0.05048082
0.05060398
0.05063271
0.05026322
public static void main(String[] args) {
// TODO code application logic herepublic static void main(String[] args) throws Exception{
for(int k = 1; k <= 100; k++)
{
int size = 10000000;//change number to different size of ranndom
int[] a = new int [size];
int[] temp = new int[a.length];
for (int i = 0; i< a.length; i++)
a[i] = (int)(Math.random()*100000 +1);
// get the start time in nanoseconds
long startTime = System.nanoTime();
// get the end time in nanoseconds
long endTime = System.nanoTime();
// calculate elapsed time in nanoseconds
long duration = endTime - startTime;
// print the elapsed time in seconds (nanaoseconds/ 1 billion)
System.out.printf("%12.8f %n", (double)duration/100000000) ;
}
}// end main()
Explanation / Answer
SelectionSortTimeTest.java
public class SelectionSortTimeTest {
public static void main(String[] args) {
// TODO code application logic herepublic static void main(String[] args) throws Exception{
int dataSet[] = {100,1000,10000};
for(int k = 0; k < dataSet.length; k++)
{
int size = 10000;//change number to different size of ranndom
int[] a = new int [dataSet[k]];
for (int i = 0; i< a.length; i++)
a[i] = (int)(Math.random()*100000 +1);
// get the start time in nanoseconds
long startTime = System.nanoTime();
selectionSort(a);
// get the end time in nanoseconds
long endTime = System.nanoTime();
// calculate elapsed time in nanoseconds
long duration = endTime - startTime;
// print the elapsed time in seconds (nanaoseconds/ 1 billion)
System.out.printf("%12.8f %n", (double)duration/100000000) ;
}
}// end main()
public static void selectionSort(int arr[]){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] > arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
}
Output:
0.00094347
0.30586981
0.91755020
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.