programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# questions on sorting algorithm

RabiDas Sharma
Ranch Hand
Posts: 69
In case of selection sort the number comparisions
made is n(n-1)/2 so complexity of it is O(n2)
Question
1>In case of selection sort As n(n-1)/2 comparisions made
and n(n-1)/2 is polynomial of degree 2
so complexity is: O(n2)

I think In case of exchange sort also number of comparisions made is
n(n-1)/2 so generalised complexity is O(n2)
but my study material says
In the worst case there are many exchanges required, i.e.(n-1)/2 exchanges are required.
In the average case n(n-1)/4 exchanges are made.
Therefore, general complexity is O (n2).
Best case complexity is O(n)

if no exchnage is made i.e,
in case of completely sorted array there is no exchange so
complexity is: O(n)
so my question is :
2>complexity depends on number of comprisions or exchanges made.??
I believe former is correct.

with regards

Campbell Ritchie
Marshal
Posts: 55772
163
Please tell us where that quote comes from.

I always thought you went for the worst‑case complexity in which case both appear to run in O() time.

Ulf Dittmer
Rancher
Posts: 42972
73
Generally one talks about worst-case complexity - that's probably what it would be used for if nothing else is specifically mentioned. But it can be worthwhile examining average-case complexity (or even best-case complexity) if you know that your data will generally adhere to the average case rather than the worst case.

complexity depends on number of comprisions or exchanges made? I believe former is correct.

No, it wouldn't be correct to put it in absolute terms like that - it's operations in general. If you wanted to cover all the bases, you'd have to use two O(n) measures, one for comparisons and one for swaps (and even more if you'd be doing other operations that depend on the size of the data).

But what you're generally interested in is the time it takes to execute a program - and a swap of two numbers takes a lot more time than a comparison of two numbers, so for sorting algorithms one generally considers just the swaps.

Just hypothetically, if a sorting algorithm had O(n^2) swaps and O(n^3) comparisons, you would likely have to have very large numbers of N before the time taken for comparisons dominates the time taken for swaps.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?