below is my bubble sort method code, but i don\'t how to write part of it. my ta
ID: 3870374 • Letter: B
Question
below is my bubble sort method code, but i don't how to write part of it. my task is to test 100, 1000, 10000 data sets.
package bubblesort;
import java.io.*;
public class BubbleSort {
public static void main(String[] args) {
for(int k = 1; k <= 100; k++)
{
int size = 50000;//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-1; i++)
a[i] = (int)(Math.random()*100000 +1);
// get the start time in nanoseconds
long startTime = System.nanoTime();
//call mergesort to sort the entire array
BubbleSort(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 BubbleSort(int[] a) {
}
}
Explanation / Answer
Please find my code.
public class BubbleSort {
public static void main(String[] args) {
int size = 100;
for(int k = 1; k <= 3; k++)
{
int[] a = new int [size];
for (int i = 0; i< a.length-1; i++)
a[i] = (int)(Math.random()*100000 +1);
// get the start time in nanoseconds
long startTime = System.nanoTime();
//call mergesort to sort the entire array
bubbleSort(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);
size = size*10;
}
}//end main
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
/*
Sample run:
0.00182916
0.05413106
1.24514958
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.