algorithm - What is the n in big-O notation? -


the question rather simple, can't find enough answer. on the upvoted question regarding big-o notation, says that:

for example, sorting algorithms typically compared based on comparison operations (comparing 2 nodes determine relative ordering).

now let's consider simple bubble sort algorithm:

for (int = arr.length - 1; > 0; i--) {     (int j = 0; j < i; j++) {         if (arr[j] > arr[j+1]) {             switchplaces(...)         }     } } 

i know worst case o(n²) , best case o(n), n exactly? if attempt sort sorted algorithm (best case), end doing nothing, why still o(n)? looping through 2 for-loops still, if should o(n²). n can't number of comparison operations, because still compare elements, right?

n size of input. array, number of elements.

to see different cases, need change algorithm:

for (int = arr.length - 1; > 0 ; i--) {     boolean swapped = false;      (int j = 0; j<i; j++) {         if (arr[j] > arr[j+1]) {             switchplaces(...);             swapped = true;         }     }      if(!swapped) {         break;     } } 

your algorithm's best/worst cases both o(n^2), possibility of returning early, best-case o(n).


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -