This week's book giveaway is in the OCAJP forum.We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!

# 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
Sheriff
Posts: 49776
69
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: 42968
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.