Reputation: 61
public class Sort{
public static void main(String[] args) {
int[] random = { 8, 32, 26, 1870, 3, 80, 46, 37 };
int[] decreasing = { 1870, 80, 46, 37, 32, 26, 8, 3 };
int[] increasing = { 3, 8, 26, 32, 37, 46, 80, 1870 };
System.out.println("|\t\t| random |decreasing|increasing|");
System.out.println("|---------------|-----------|-----------|----------|");
System.out.println("|Bubblesort\t| " + bubbleSort(random) + " ms\t|" + bubbleSort(decreasing) + " ms\t|"
+ bubbleSort(increasing) + " ms\t|");
}
public static long bubbleSort(int[] arr) {
long start = System.currentTimeMillis();
for (int j = 0; j < arr.length - 1; j++) {
for (int i = 0; i < arr.length - j - 1; i++) {
if (arr[i + 1] < arr[i]) {
arr[i + 1] = arr[i] + arr[i + 1];
arr[i] = arr[i + 1] - arr[i];
arr[i + 1] = arr[i + 1] - arr[i];
}
}
}
return System.currentTimeMillis() - start;
}
}
Output:
I wrote a program that executes bubbleSort method and returns the time it took in ms. I want to print the return value but I get 0 for all arrays. When I debug the program, I can see that its returning some other number. But when it comes to print, its printing 0. I dont understand the problem. Can someone please help me?
Upvotes: 3
Views: 157
Reputation: 1742
Try using System.nanoTime()
in place of System.currentTimeMillis()
. The nanoTime function uses nanoseconds as the unit, instead of milliseconds, making it very unlikely that no time has elapsed while the program was running.
But, really you need to test much longer arrays -- try thousands or tens of thousands of elements. You aren't going to get actually useful timing data from sorting such a short array. You will probably want to write code that generates arrays full of many random elements, and then uses a built-in method such as Arrays.sort to sort the random data into the decreasing or increasing test lists.
If I wanted to hold a race to determine who was the fastest runner, and I set a course that was one centimeter (or one inch) long, would I be able to determine anything useful from the results? Probably not. But, if the course was 100 meters, or 400 meters, or 5 kilometers, then I would be able to learn something useful from the results.
Upvotes: 2