简体   繁体   中英

Does the number of comparisons in an algorithm differ from its complexity? If so, how?

I just started learning about algorithms and time complexity.

I noticed that, for certain algorithms, their time complexity is measured based on the number of comparisons made. I'm confused. Are they different?

Comparisons are only used to measure the efficiency of sorting algorithms or similar. It's not the same as runtime complexity.

The idea is that, instead of simple integers, the array that you're sorting might contain things that take a long time to compare. An array of of strings, for example, can be bubble-sorted using N(N-1)/2 string comparisons, even though a single string comparison might require many other operations, including many comparisons of individual characters.

Measuring the performance of a sorting algorithm in terms of the number of comparisons makes the measurement independent of the type of things being sorted. Usually you'll also want to know how many moves or swaps it makes.

I suppose you're learning about time complexity for sorting algorithms.

The time complexity of an algorithm is the number of elementary operations that it has to do for a certain input size.

So, going back to your question, why do certain algorithms specify the number of comparisons?

It's because, while for simplicity we consider comparisons, swaps and other operations as elementary operations , they can't be all treated in the same way.

Let us suppose we have 2 algorithms that complete the same task:

  1. Algorithm A that does n^2 comparisons and n swaps
  2. Algorithm B that does n swaps and n^2 comparisons

For the same input size, it would seem that they both take the same amount of elementary operations. Let us suppose we have a computer that takes 1 second to do comparisons and 5 seconds to do swaps (obviously the numbers aren't realistic but stay with me), which algorithm would you use?

Let us suppose we have an input size of 100:

  1. Algorithm A takes 10,500s
  2. Algorithm B takes 50,100s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM