JAVA BubbleSort Output Plotting
Posted
by
John Smith
on Stack Overflow
See other posts from Stack Overflow
or by John Smith
Published on 2012-12-08T11:00:39Z
Indexed on
2012/12/08
11:04 UTC
Read the original article
Hit count: 420
I'm not sure how to plot the output I get with my run time results for BubbleSort.
Here's the thing: I've written a working BubbleSort algorithm that does exactly as it should. But I wish to plot the output, to show the following:
Best Case, Worst Case, Average Case ... How would I go about plotting it on a graph?
Here is the code:
public class BubbleSort {
static double bestTime = 10000000, worstTime = 0;
public static void main(String[] args) {
int BubArray[] = new int[]{13981, 6793, 2662, 10986, 733, ... #1000 integers};
System.out.println("Unsorted List Before Bubble Sort");
for(int a = 0; a < BubArray.length; a++){
System.out.print(BubArray[a] + " ");
}
System.out.println("\n Bubble Sort Execution ...");
for(int i=0; i<10000;i++) {
bubbleSortTimeTaken(BubArray, i);
}
int itrs = bubbleSort(BubArray);
System.out.println("");
System.out.println("Array After Bubble Sort");
System.out.println("Moves Taken for Sort : " + itrs + " Moves.");
System.out.println("BestTime: " + bestTime + " WorstTime: " + worstTime);
System.out.print("Sorted Array: \n");
for(int a = 0; a < BubArray.length; a++){
System.out.print(BubArray[a] + " ");
}
}
private static int bubbleSort(int[] BubArray) {
int z = BubArray.length;
int temp = 0;
int itrs = 0;
for(int a = 0; a < z; a++){
for(int x=1; x < (z-a); x++){
if(BubArray[x-1] > BubArray[x]){
temp = BubArray[x-1];
BubArray[x-1] = BubArray[x];
BubArray[x] = temp;
}
itrs++;
}
}
return itrs;
}
public static void bubbleSortTimeTaken(int[] BubArray, int n)
{
long startTime = System.nanoTime();
bubbleSort(BubArray);
double timeTaken = (System.nanoTime() - startTime)/1000000d;
if (timeTaken > 0)
{
worstTime = timeTaken;
}
else if (timeTaken < bestTime)
{
bestTime = timeTaken;
}
System.out.println(n + "," + timeTaken);
}
}
The output are as the following ( execution number, time (nano/10^6):
Unsorted List Before Bubble Sort
13981 6793 2662 .... #1000 integers
Bubble Sort Execution ...
0, 18.319891
1, 4.728978
2, 3.670697
3, 3.648922
4, 4.161576
5, 3.824369
....
9995, 4.331423
9996, 3.692473
9997, 3.709893
9998, 6.16055
9999, 4.32209
Array After Bubble Sort
Moves Taken for Sort : 541320 Moves.
BestTime: 1.0E7 WorstTime: 4.32209
Sorted Array:
10 11 17 24 57 60 83 128 141 145 ... #1000 integers
I am looking for graphs to represent Average, Best and Worst case based on the output but my current graphs don't look correct.
Any help would be appreciated, thanks.
© Stack Overflow or respective owner