Što je objašnjenje velikog O zapisa: Složenost prostora i vremena

Doista razumijete Big O? Ako jeste, ovo će vam osvježiti razumijevanje prije razgovora. Ako ne, ne brinite - dođite i pridružite nam se u nekim poduhvatima u računalnoj znanosti.

Ako ste pohađali neke tečajeve vezane uz algoritam, vjerojatno ste čuli za pojam Big O notation . Ako niste, ovdje ćemo to preispitati, a zatim ćemo dublje razumjeti što je to zapravo.

Oznaka Big O jedan je od najvažnijih alata za računalne znanstvenike da analiziraju cijenu algoritma. Dobra je praksa da softverski inženjeri razumiju i dublje.

Ovaj je članak napisan s pretpostavkom da ste se već pozabavili nekim kodom. Također, neki dubinski materijali također zahtijevaju srednjoškolske osnove matematike, pa stoga mogu biti nešto manje ugodni za početnike. Ali ako ste spremni, krenimo!

U ovom ćemo članku detaljno raspraviti o notaciji Big O. Počet ćemo s primjerom algoritma kako bismo otvorili svoje razumijevanje. Zatim ćemo malo ući u matematiku da bismo imali formalno razumijevanje. Nakon toga ćemo proći kroz neke uobičajene varijacije notacije Big O. Na kraju ćemo razgovarati o nekim ograničenjima Big O-a u praktičnom scenariju. Sadržaj možete pronaći u nastavku.

Sadržaj

  1. Što je oznaka Big O i zašto je to važno
  2. Formalna definicija oznake Big O
  3. Veliki O, Mali O, Omega & Theta
  4. Usporedba složenosti tipičnih velikih osova
  5. Složenost vremena i prostora
  6. Najbolja, prosječna, najgora, očekivana složenost
  7. Zašto Big O nije važan
  8. Na kraju…

Pa krenimo.

1. Što je Big O Notation i zašto je to važno

„Big O notacija je matematička notacija koja opisuje ograničavajuće ponašanje funkcije kada argument teži određenoj vrijednosti ili beskonačnosti. Član je obitelji notacija koje su izmislili Paul Bachmann, Edmund Landau i drugi, zajednički nazvani Bachmann – Landau notacija ili asimptotska notacija. "- Wikipedijina definicija notacije Big O

Jednostavnim riječima, oznaka Big O opisuje složenost vašeg koda pomoću algebarskih izraza.

Da bismo razumjeli što je oznaka Big O, možemo pogledati tipičan primjer, O (n²) , koji se obično izgovara "Big O na kvadrat" . Slovo "n" ovdje predstavlja veličinu unosa , a funkcija "g (n) = n²" unutar "O ()" daje nam predodžbu koliko je algoritam složen s obzirom na veličinu unosa.

Tipičan algoritam koji ima složenost O (n²) bio bi algoritam sortiranja odabira . Izbor vrsta je algoritam za sortiranje koji iterira po popisu kako bi se osiguralo svaki element u indeks i je -ti najmanji / najveći element liste. CODEPEN nastavku daje vizualni primjer toga.

Algoritam se može opisati sljedećim kodom. Kako bi se osiguralo da je i- ti element i- ti najmanji element na popisu, ovaj algoritam prvo prolazi kroz popis pomoću petlje for. Zatim za svaki element koristi drugu for petlju kako bi pronašao najmanji element u preostalom dijelu popisa.

SelectionSort(List) { for(i from 0 to List.Length) { SmallestElement = List[i] for(j from i to List.Length) { if(SmallestElement > List[j]) { SmallestElement = List[j] } } Swap(List[i], SmallestElement) } }

U ovom scenariju varijablu List smatramo ulazom, pa je veličina ulaza n broj elemenata unutar Popisa . Pretpostavimo da izraz if i dodjela vrijednosti ograničene naredbom if trebaju konstantno vrijeme. Tada možemo pronaći veliku O oznaku za funkciju SelectionSort analizirajući koliko se puta izvršavaju izrazi.

Prvo unutarnja petlja for pokreće izraze unutar n puta. I onda nakon što sam se povećava, unutarnji za petlje staze za n-1 puta ... ... dok to radi jednom, a zatim i od for petlje do svoje uvjete ukida.

Ovo zapravo završava davanjem geometrijskog zbroja, a s nekim srednjoškolskim matematičkim postupcima otkrili bismo da će se unutarnja petlja ponoviti 1 + 2 ... + n puta, što je jednako n (n-1) / 2 puta. Ako ovo pomnožimo, na kraju ćemo dobiti n² / 2-n / 2.

Kada izračunavamo veliku O oznaku, brinemo samo o dominantnim članovima , a ne brinemo o koeficijentima. Stoga uzimamo n² kao krajnje veliko O. Zapisujemo ga kao O (n²), što se opet izgovara "Veliki O na kvadrat" .

Sad se možda pitate, o čemu se zapravo radi u ovom "dominantnom izrazu" ? A zašto nas nije briga za koeficijente? Ne brinite, pregledat ćemo ih jednog po jednog. Možda je malo teško razumjeti na početku, ali sve će to imati puno više smisla dok čitate sljedeći odjeljak.

2. Formalna definicija oznake Big O

Jednom davno postojao je indijski kralj koji je želio nagraditi mudrog čovjeka za njegovu izvrsnost. Mudri čovjek nije tražio ništa osim pšenice koja bi napunila šahovsku ploču.

Ali ovdje su bila njegova pravila: na prvoj pločici želi 1 zrno pšenice, zatim 2 na drugoj pločici, pa 4 na sljedećoj ... svaku pločicu na šahovskoj ploči trebalo je napuniti dvostrukom količinom zrna kao prethodna jedan. Naivni se kralj bez oklijevanja složio, misleći da će to biti beznačajan zahtjev za ispunjenje, sve dok zapravo nije nastavio i pokušao ...

Pa koliko zrna pšenice kralj duguje mudrom čovjeku? Znamo da šahovska ploča ima 8 kvadrata sa 8 kvadrata, što ukupno iznosi 64 pločice, tako da bi konačna pločica trebala imati 2⁶⁴ zrna pšenice. Ako izračunate putem interneta, na kraju ćete dobiti 1,8446744 * 10¹⁹, to je oko 18, a zatim 18 nula. Pod pretpostavkom da svako zrno pšenice teži 0,01 grama, to nam daje 184.467.440.737 tona pšenice. A 184 milijarde tona prilično je puno, zar ne?

The numbers grow quite fast later for exponential growth don’t they? The same logic goes for computer algorithms. If the required efforts to accomplish a task grow exponentially with respect to the input size, it can end up becoming enormously large.

Now the square of 64 is 4096. If you add that number to 2⁶⁴, it will be lost outside the significant digits. This is why, when we look at the growth rate, we only care about the dominant terms. And since we want to analyze the growth with respect to the input size, the coefficients which only multiply the number rather than growing with the input size do not contain useful information.

Below is the formal definition of Big O:

The formal definition is useful when you need to perform a math proof. For example, the time complexity for selection sort can be defined by the function f(n) = n²/2-n/2 as we have discussed in the previous section.

If we allow our function g(n) to be n², we can find a constant c = 1, and a N₀ = 0, and so long as N > N₀, N² will always be greater than N²/2-N/2. We can easily prove this by subtracting N²/2 from both functions, then we can easily see N²/2 > -N/2 to be true when N > 0. Therefore, we can come up with the conclusion that f(n) = O(n²), in the other selection sort is “big O squared”.

You might have noticed a little trick here. That is, if you make g(n) grow supper fast, way faster than anything, O(g(n)) will always be great enough. For example, for any polynomial function, you can always be right by saying that they are O(2ⁿ) because 2ⁿ will eventually outgrow any polynomials.

Mathematically, you are right, but generally when we talk about Big O, we want to know the tight bound of the function. You will understand this more as you read through the next section.

But before we go, let’s test your understanding with the following question. The answer will be found in later sections so it won’t be a throw away.

Pitanje: Slika je predstavljena 2D nizom piksela. Ako upotrijebite ugniježđenu petlju for za itiriranje kroz svaki piksel (to jest, imate petlju for koja prolazi kroz sve stupce, a zatim drugu za petlju koja prolazi unutar svih redaka), kolika je vremenska složenost algoritma kada se slika se smatra ulazom?

3. Veliki O, Mali O, Omega & Theta

Veliko O: „f (n) je O (g (n))“ iff za neke konstante c i N₀, f (N) ≤ cg (N) za sve N> N₀Omega: „f (n) je Ω (g ( n)) "iff za neke konstante c i N₀, f (N) ≥ cg (N) za sve N> N₀Teta:" f (n) je Θ (g (n)) "ako je f (n) O (g (n)) i f (n) je Ω (g (n)) Mali O: „f (n) je o (g (n))“ ako je f (n) O (g (n)) i f ( n) nije Θ (g (n)) - formalna definicija velikog O, Omega, Theta i Malog O

Jednostavnim riječima:

  • Big O (O()) describes the upper bound of the complexity.
  • Omega (Ω()) describes the lower bound of the complexity.
  • Theta (Θ()) describes the exact bound of the complexity.
  • Little O (o()) describes the upper bound excluding the exact bound.

For example, the function g(n) = n² + 3n is O(n³), o(n⁴), Θ(n²) and Ω(n). But you would still be right if you say it is Ω(n²) or O(n²).

Generally, when we talk about Big O, what we actually meant is Theta. It is kind of meaningless when you give an upper bound that is way larger than the scope of the analysis. This would be similar to solving inequalities by putting ∞ on the larger side, which will almost always make you right.

But how do we determine which functions are more complex than others? In the next section you will be reading, we will learn that in detail.

4. Complexity Comparison Between Typical Big Os

When we are trying to figure out the Big O for a particular function g(n), we only care about the dominant term of the function. The dominant term is the term that grows the fastest.

For example, n² grows faster than n, so if we have something like g(n) = n² + 5n + 6, it will be big O(n²). If you have taken some calculus before, this is very similar to the shortcut of finding limits for fractional polynomials, where you only care about the dominant term for numerators and denominators in the end.

But which function grows faster than the others? There are actually quite a few rules.

1. O(1) has the least complexity

Often called “constant time”, if you can create an algorithm to solve the problem in O(1), you are probably at your best. In some scenarios, the complexity may go beyond O(1), then we can analyze them by finding its O(1/g(n)) counterpart. For example, O(1/n) is more complex than O(1/n²).

2. O(log(n)) is more complex than O(1), but less complex than polynomials

As complexity is often related to divide and conquer algorithms, O(log(n)) is generally a good complexity you can reach for sorting algorithms. O(log(n)) is less complex than O(√n), because the square root function can be considered a polynomial, where the exponent is 0.5.

3. Complexity of polynomials increases as the exponent increases

For example, O(n⁵) is more complex than O(n⁴). Due to the simplicity of it, we actually went over quite many examples of polynomials in the previous sections.

4. Exponentials have greater complexity than polynomials as long as the coefficients are positive multiples of n

O(2ⁿ) is more complex than O(n⁹⁹), but O(2ⁿ) is actually less complex than O(1). We generally take 2 as base for exponentials and logarithms because things tends to be binary in Computer Science, but exponents can be changed by changing the coefficients. If not specified, the base for logarithms is assumed to be 2.

5. Factorials have greater complexity than exponentials

If you are interested in the reasoning, look up the Gamma function, it is an analytic continuation of a factorial. A short proof is that both factorials and exponentials have the same number of multiplications, but the numbers that get multiplied grow for factorials, while remaining constant for exponentials.

6. Multiplying terms

When multiplying, the complexity will be greater than the original, but no more than the equivalence of multiplying something that is more complex. For example, O(n * log(n)) is more complex than O(n) but less complex than O(n²), because O(n²) = O(n * n) and n is more complex than log(n).

To test your understanding, try ranking the following functions from the most complex to the lease complex. The solutions with detailed explanations can be found in a later section as you read. Some of them are meant to be tricky and may require some deeper understanding of math. As you get to the solution, you will understand them more.

Pitanje: Poredajte sljedeće funkcije od najsloženijih do najmoprimilnijih. Rješenje za 2. odjeljak Pitanje: To je zapravo trebalo biti trik pitanje kako biste provjerili svoje razumijevanje. Pitanje vas pokušava natjerati da odgovorite O (n²) jer postoji ugniježđena petlja for. Međutim, n bi trebala biti ulazna veličina. Budući da je slikovni niz ulaz, a svaki je piksel ponovljen samo jednom, odgovor je zapravo O (n). Sljedeći će odjeljak obraditi još primjera poput ovog.

5. Vrijeme i prostorna složenost

So far, we have only been discussing the time complexity of the algorithms. That is, we only care about how much time it takes for the program to complete the task. What also matters is the space the program takes to complete the task. The space complexity is related to how much memory the program will use, and therefore is also an important factor to analyze.

The space complexity works similarly to time complexity. For example, selection sort has a space complexity of O(1), because it only stores one minimum value and its index for comparison, the maximum space used does not increase with the input size.

Some algorithms, such as bucket sort, have a space complexity of O(n), but are able to chop down the time complexity to O(1). Bucket sort sorts the array by creating a sorted list of all the possible elements in the array, then increments the count whenever the element is encountered. In the end the sorted array will be the sorted list elements repeated by their counts.

6. Best, Average, Worst, Expected Complexity

The complexity can also be analyzed as best case, worst case, average case and expected case.

Let’s take insertion sort, for example. Insertion sort iterates through all the elements in the list. If the element is larger than its previous element, it inserts the element backwards until it is larger than the previous element.

If the array is initially sorted, no swap will be made. The algorithm will just iterate through the array once, which results a time complexity of O(n). Therefore, we would say that the best-case time complexity of insertion sort is O(n). A complexity of O(n) is also often called linear complexity.

Sometimes an algorithm just has bad luck. Quick sort, for example, will have to go through the list in O(n) time if the elements are sorted in the opposite order, but on average it sorts the array in O(n * log(n)) time. Generally, when we evaluate time complexity of an algorithm, we look at their worst-case performance. More on that and quick sort will be discussed in the next section as you read.

The average case complexity describes the expected performance of the algorithm. Sometimes involves calculating the probability of each scenarios. It can get complicated to go into the details and therefore not discussed in this article. Below is a cheat-sheet on the time and space complexity of typical algorithms.

Solution to Section 4 Question:

By inspecting the functions, we should be able to immediately rank the following polynomials from most complex to lease complex with rule 3. Where the square root of n is just n to the power of 0.5.

Then by applying rules 2 and 6, we will get the following. Base 3 log can be converted to base 2 with log base conversions. Base 3 log still grows a little bit slower then base 2 logs, and therefore gets ranked after.

The rest may look a little bit tricky, but let’s try to unveil their true faces and see where we can put them.

First of all, 2 to the power of 2 to the power of n is greater than 2 to the power of n, and the +1 spices it up even more.

And then since we know 2 to the power of log(n) with based 2 is equal to n, we can convert the following. The log with 0.001 as exponent grows a little bit more than constants, but less than almost anything else.

The one with n to the power of log(log(n)) is actually a variation of the quasi-polynomial, which is greater than polynomial but less than exponential. Since log(n) grows slower than n, the complexity of it is a bit less. The one with the inverse log converges to constant, as 1/log(n) diverges to infinity.

Čimbenici se mogu prikazati množenjem i na taj se način mogu pretvoriti u zbrajanja izvan logaritamske funkcije. "N odaberite 2" može se pretvoriti u polinom s najvećim kubnim članom.

I na kraju, funkcije možemo rangirati od najsloženijih do najmanje složenih.

Zašto BigO nije važno

!!! - UPOZORENJE - !!! Sadržaj o kojem se ovdje raspravlja uglavnom ne prihvaća većina programera u svijetu. Raspravite o tome na vlastiti rizik u intervjuu. Ljudi su zapravo blogovali o tome kako su propali na Googleovim intervjuima jer su dovodili u pitanje autoritet, kao ovdje. !!! - UPOZORENJE - !!!

Since we have previously learned that the worst case time complexity for quick sort is O(n²), but O(n * log(n)) for merge sort, merge sort should be faster — right? Well you probably have guessed that the answer is false. The algorithms are just wired up in a way that makes quick sort the “quick sort”.

To demonstrate, check out this trinket.io I made. It compares the time for quick sort and merge sort. I have only managed to test it on arrays with a length up to 10000, but as you can see so far, the time for merge sort grows faster than quick sort. Despite quick sort having a worse case complexity of O(n²), the likelihood of that is really low. When it comes to the increase in speed quick sort has over merge sort bounded by the O(n * log(n)) complexity, quick sort ends up with a better performance in average.

I have also made the below graph to compare the ratio between the time they take, as it is hard to see them at lower values. And as you can see, the percentage time taken for quick sort is in a descending order.

The moral of the story is, Big O notation is only a mathematical analysis to provide a reference on the resources consumed by the algorithm. Practically, the results may be different. But it is generally a good practice trying to chop down the complexity of our algorithms, until we run into a case where we know what we are doing.

In the end…

I like coding, learning new things and sharing them with the community. If there is anything in which you are particularly interested, please let me know. I generally write on web design, software architecture, mathematics and data science. You can find some great articles I have written before if you are interested in any of the topics above.

Hope you have a great time learning computer science!!!