I have written a program in java using selection, bubble and merge sort and I have to print just the time it took to run the sort which works just fine, but how do I sort a sorted list?

I want to see how much faster is it to sort a sorted list, time wise. I'm running the sort on a million integers generated randomly.

Any help would be appreciated.

here's my selection sort......
(btw all my sorts using the same numbers once been generated randomly.

``````for(int i = 0; i < 10000; i++) {
Array[i] = rn.nextInt(10000);
//System.out.println(Array[i]);
}

Array2 = Arrays.copyOf(Array, 10000);
startSelection = System.nanoTime();
for( int fill = 0; fill < 99999; fill++) {
for (int compare = fill + 1; compare < 10000; compare++) {
if (Array[fill] > Array[compare]) {
int temp = Array[fill];
Array[compare] = temp;
}
}
}
endSelection = System.nanoTime();
resultSelection = endSelection - startSelection;

double seconds = resultSelection / 1000000000.0;

System.out.println(" It took " + resultSelection + " nanoseconds and " + seconds + " seconds to do the selction sort");

output:

It took 33403766 nanoseconds and 0.033403766 seconds to do the selction sort
``````

## All 5 Replies

A "SORTED" List is already sorted, that's why it's called a 'sorted' list.

Create the random data
run the sort and see how long it takes
now run the sort again - this time the data will already be sorted - and see how much quicker that is

here's what i wanna do, re-run the sorts on sorted arrays, of which I have three that
are the same and time these too.

James - could you please provide an example. its my understanding that once the data is run the numbers generated by the randomizer will be different for second run. and since its an array of numbers not been saved anywhere It will keep giving me differnt results.

stultuske --- i know its sorted. I dont want to sort a sorted array, rather run it again so i can compare the difference between a sorted and an un-sorted array. except i don't know how to re-run the sorted array to find the time once its already sorted.

thanks

Lines 1-4 of your code set up the random data.
Lines 7-21 do the sort and report the timing

So repeat lines 7-21, but don't repeat lines 1-4

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.