big o - Time complexity(Java, Quicksort) -
i have general question calculating time complexity(big o notation). when people worst time complexity quicksort o(n^2) (picking first element of array pivot every time, , array inversely sorted), operation account o(n^2)? people count comparisons made if/else statements? or count total number of swaps makes? how know "steps" count calculate big o notation.
i know basic question i've read articles on google still haven't figured out
worst cases of quick sort
worst case of quick sort when array inversely sorted, sorted , elements equal.
understand big-oh
having said that, let first understand big-oh of means.
when have , asymptotic upper bound, use o-notation. given function g(n), denote o(g(n)) set of functions, o(g(n)) = { f(n) : there exist positive c , no,
such 0<= f(n) <= cg(n) n >= no}
how calculate big-oh?
big-oh means how program's complexity increases input size.
here code:
import java.util.*; class quicksort { static int partition(int a[],int p,int r) { int x = a[r]; int i=p-1; for(int j=p;j<=r-1;j++) { if(a[j]<=x) { i++; int t = a[i]; a[i] = a[j]; a[j] = t; } } int temp = a[i+1]; a[i+1] = a[r]; a[r] = temp; return i+1; } static void quicksort(int a[],int p,int r) { if(p<r) { int q = partition(a,p,r); quicksort(a,p,q-1); quicksort(a,q+1,r); } } public static void main(string[] args) { int a[] = {5,9,2,7,6,3,8,4,1,0}; quicksort(a,0,9); arrays.stream(a).foreach(system.out::println); } }
take consideration following statements:
block 1:
int x = a[r]; int i=p-1;
block 2:
if(a[j]<=x) { i++; int t = a[i]; a[i] = a[j]; a[j] = t; }
block 3:
int temp = a[i+1]; a[i+1] = a[r]; a[r] = temp; return i+1;
block 4:
if(p<r) { int q = partition(a,p,r); quicksort(a,p,q-1); quicksort(a,q+1,r); }
assuming each statements take constant time c. let's calculate how many times each block calculated.
the first block executed 2c times. second block executed 5c times. thirst block executed 4c times.
we write o(1) implies number of times statement executed same number of times when size of input varies. 2c, 5c , 4c o(1).
but, when add loop on second block
for(int j=p;j<=r-1;j++) { if(a[j]<=x) { i++; int t = a[i]; a[i] = a[j]; a[j] = t; } }
it runs n times (assuming r-p equal n, size of input) i.e., no(1) times i.e., o(n). doesn't run n times everytime. hence, have average case o(log n) i.e, @ least log(n) elements traversed.
we established partition runs o(n) or o(log n). last block, quicksort method, definetly runs in o(n). can think of enclosing loop runs n times. hence entire complexity either o(n2) or o(nlog n).
Comments
Post a Comment