problem with System.nanoTime()
hello, and thanks for any help in advance
im having a little problem with trying to measure the time taken by a couple of algorithms to solve a problem. When the application starts the user presses a button which generates a random array of 10 integers (there is also another button which allows user to enter the 10 integers manually):
Code:
. ...if(e.getSource() == randB)
{
Random r = new Random();
aDisplay.setText("The current array is: {");
for(int x = 0; x < 10; x++)
{
array[x] = 1 + r.nextInt(100);
aDisplay.append(array[x] + ", ");
}
aDisplay.append("}");
}
each algorithm is in a separate class from the above code and the algorithms used to sort the array is determined by a checkboxes:
Code:
public void itemStateChanged(ItemEvent e)
{
bubbleSelected = bubbleC.isSelected()? true: false;
selectionSelected = selectionC.isSelected()? true: false;
mergeSelected = mergeC.isSelected()? true: false;
quickSelected = quickC.isSelected()? true: false;
}
next a button is pressed which will sort the array with all the selected algorithms and display the time it took,eg if "bubbleC" checkbox was selected:
Code:
display.setText(" ");
if(bubbleSelected == true)
{
bub.setArray(array);
int bubA[] = new int[10];
display.append("~~~~~~~~~~~~~~~~~~Bubble Sort~~~~~~~~~~~~~~~~~~\n");
long bStart = System.nanoTime();
bubA = bub.sort();
long bEnd = System.nanoTime();
long bTook = bEnd - bStart;
display.append("The sorted array is: {");
for(int x = 0; x < 10; x++)
{
display.append(bubA[x] + ", ");
}
display.append("}\n");
display.append("The time taken to sort the array is: " + bTook + " nanoseconds\n\n");
}
bub is a BubbleSort object. here is the BubbleSort class:
Code:
public class BubbleSort
{
private int A[];
public BubbleSort()
{
A = new int[1];
A[0] = 0;
}
public BubbleSort(int array[])
{
A = array;
}
public int[] sort()
{
int temp;
for(int x = 0; x < A.length; x++)
{
for(int y = 0; y < ( (A.length)-1 ); y++)
{
if(A[y] > A[y+1])
{
temp = A[y+1];
A[y+1] = A[y];
A[y] = temp;
}
}
}
return A;
}
public void setArray(int array[])
{
A = array;
}
}
the problem im getting is that when i initially press the sort button ill get a time taken of like around 25000 nanoseconds, however if i press the sort button again without changing the original unsorted array ill progressively get a lower and lower time. If i keep pressing it for a while it goes down to as low as less than 3000 nanoseconds when theoretically i should be getting back the same time since im using the same algorithm on the same array.
on the other hand if i generate a new random array after each time i press the sort button it seems to work fine
i dont know why this is happening because each time i press the sort button the original unsorted array is sent to bub and the array "bubA[]" which stores the sorted array returned by "bub.sort()" is cleared:
Code:
...if(bubbleSelected == true)
{
bub.setArray(array);
int bubA[] = new int[10];
any help would be greatly appreciated