Reputation: 2938
If bubble sort takes 200 sec to sort 200 names then how many items it can sort in 800 secs?
Calculating number of comparisons can give us the solution. How can we calculate the number of comparisons it takes to sort 200 names ? Do we have to consider the best case ?
Upvotes: 0
Views: 4716
Reputation: 16406
800 is 4 x 200. Bubble sort is O(n*n), so on average you can sort twice as many items in 4 times the time, so the expectation is 400 names, on average, if 200 was an average case.
Upvotes: 1
Reputation: 55856
(n-1) + (n-2) + .. +1
. Do some maths again?(obviously you can write a smart bubble sort that does not sort an already sorted array)
BUBBLESORT A
for i = 1 to A.length 1
for j = A.length downto i+1
if A[j] < A[j - 1]
exchange A[j] with A[j-1]
from The Introduction to Algorithms - CLRS
[1] On #3. See http://en.wikipedia.org/wiki/Bubble_sort it mentions an optimized inner loop that identified the sorted remaining array and makes a best case O(n) -- sorry about that.
Upvotes: 1