i'm trying understand complexity class algorithms off of professor's lecture notes, still can't hang of it.
void sort(int a[], int n) { //n length of array (int base=0; base<n; ++base) (int check=base+1; check<n; ++check) if (a[base] > a[check]) std::swap(a[base], a[check]); }
on notes says expression 8n^2+12n+6.
from understand complexity class n^2 because fastest growing out of rest. ignore constants because they're irrelevant when going infinity.
however, want know how got constants.
i don't understand how got + 6. run total of 6 times when function called once? see int base = 0 created once because belongs on outer for-loop.
edit: found how + 6 bare minimum function needs run. in case for-loops executed once... total lines? make copy of a[] , int n, have our for-loops , if statement. altogether adds 6.
what 12n?
as ami tavory suggest looks bullshit. after more close still weird expression mixing cycles of different operations atomic ... if ignore relevancy see this:
void sort(int a[], int n) { // ?t (int base=0; base<n; ++base) // 1 +(3+2)n (int check=base+1; check<n; ++check) // 2n+(3+2)m if (a[base] > a[check]) // (2+1+2)m std::swap(a[base], a[check]); // (2+2+2)m }
where did wild assumptions how many cycles memory/register/direct access or alu operations. m = ~ (n^2)/2
(sorry lazy actual count series sum) number of inner loop iterations. when sum got:
16*(n^2)/2+7n+1+? 8*n^2 + 7n + 1+?
which pretty close expression. used inaccurate m
, not know architecture behind result might change bit possibly in favor of expression. function init , return accounted ~5
cycles. if got wilder that:
int a[]; // 2 // heap -> reg int n; // 2 // heap -> reg {} // 1 // stack return (i guess should 2)
so got:
8*n^2 + 7n + 6
against yours:
8*n^2 + 12n + 6
to make accurate should:
- compute
m
exactly - get timings of operations architecture for
break code atomic operations
distinguishing direct/memory(heap/stack)/register access (may read/write), alu operations , more... example
swap(a,b) { c=a; a=b; b=c; }
if not done xoring ... , can count cycles tried ...for example here machine cycle timings z80 link zilog z80a complete instruction set machine cycle timing. can see how different each type of instruction is. should have similar platform/architecture learning stuff on.
Comments
Post a Comment