Reputation: 139
I've written a bubble sort program that sorts 10000 unique values into order.
I've run the program and it gives me an output of time (using nanoTime) for the time it takes the program to complete, but I wish to add another output to the program's code; How many moves the program takes to sort from start to finish.
Here is the code:
public class BubbleSort {
public static void main(String[] args) {
int BubArray[] = new int[]{#here are 10000 integers#};
System.out.println("Array Before Bubble Sort");
for(int a = 0; a < BubArray.length; a++){
System.out.print(BubArray[a] + " ");
}
double timeTaken = bubbleSortTimeTaken(BubArray);
bubbleSort(BubArray);
System.out.println("");
System.out.println("Array After Bubble Sort");
System.out.println(" Time taken for Sort : " + timeTaken + " milliseconds.");
for(int a = 0; a < BubArray.length; a++){
System.out.print(BubArray[a] + " ");
}
}
private static void bubbleSort(int[] BubArray) {
int z = BubArray.length;
int temp = 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;
}
}
}
}
public static double bubbleSortTimeTaken(int[] BubArray) {
long startTime = System.nanoTime();
bubbleSort(BubArray);
long timeTaken = System.nanoTime() - startTime;
return timeTaken;
}
}
The code executes and outputs how I want it to:
Array Before Bubble Sort
13981 6793 2662 10986 733 10107 2850 ...
Array After Bubble Sort
10 11 17 24 35 53 57 60 61 78 83 89 128 131 138 141 ....
Time taken for Sort : 1.6788472E7 milliseconds.
But I wish to add another output to the code where it tells me in how many moves (basically a move counter) it takes to complete, i.e:
Time taken for Sort : 1.6788472E7 milliseconds.
Total number of moves: 3000
Does this make sense? Any help would be appreciated, thanks.
Upvotes: 1
Views: 819
Reputation: 31238
I would change bubbleSort
to return an int and assign your time complexity to it.
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;
}
Then in main
:
int itrs = bubbleSort(BubArray);
System.out.println("");
System.out.println("Array After Bubble Sort");
System.out.println(" Time taken for Sort : " + timeTaken + " milliseconds.");
System.out.println("Time complexity: " + itrs);
Upvotes: 1
Reputation:
Try this:
// returns the number of switches
private int bubbleSort(int[] BubArray) {
int z = BubArray.length;
int temp = 0;
int timesSwitched = 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;
timesSwitched++
}
}
}
return timesSwitched;
}
Upvotes: 1