26

Possible Duplicate:
Plain English explanation of Big O

In the answer to a programming puzzle it said sorting a string takes O(n log n) time. How is that derived?

Does anybody have a good reference link for Big O resources.

Thanks

Community
  • 1
  • 1
Percy Flarge
  • 427
  • 1
  • 5
  • 6

2 Answers2

25

Why is sorting a string O(n log n)?

Sorting the characters in a string is not necessarily O(n log n).

  • O(n log n) is the optimal value for a comparison sort. It is also the complexity of many languages' default sort implementation. However it's certainly possible to do worse than this. The complexity of sorting the characters in a string depends on the specific algorithm you choose to solve this task.
  • It's also possible to do better than O(n log n) in some cases by using a sorting algorithm which is not a comparison sort. For example, if you know that you have an ASCII string with a maximum of 127 distinct characters you could use a counting sort which is O(n). A counting sort would also be feasible for Unicode strings where all characters are in in the Basic Multilingual Plane.
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

A definition and some examples of Big O can be found by using a search engine, e.g. here:

An explanation of sort algorithms based on comparing elements, together with an explanation for the lower bound on the number of required comparisons, can be found here:

Christian Semrau
  • 8,913
  • 2
  • 32
  • 39