Jump to content
nikel1992

Complexitate

Recommended Posts

Posted

Am si eu nevoie , daca ma poate ajuta sa imi zica si mie cineva complexitatea acestui program.

void function(int* a, int n){

int m=0,aux;

for(int i=0;i<n/2;i++){

for(int j=i+1;j<n;j++){

if(a[j]<a){

aux=a; a=a[j]; a[j]=aux;

}

}

}

}

Posted (edited)

for(int i=0;i<n/2;i++){

for(int j=i+1;j<n;j++){

Edit: Scuze, nu e ok, primul "for" merge doar pana la n/2.

Avem: (n-1)+(n-2)+...+(n-n/2). Adica mult mai putin.

De ce?

La i == 0 avem (n-1) pasi

La i == 1 avem (n-2) pasi

...

La i == n/2 - 1 avem (n - n/2) pasi

Rezultatul e suma acestor adunari.

Mai exact: n(n-1)/2 - ( n/2 * (n/2 + 1) )/2

Adica suma lui Gauss de la 1 la n-1 din care scadem suma lui Gauss de la 1 la n/2.

Cred ca rezultatul final e:

3n(n-2) / 8.

Sper ca nu m-am incurcat pe acolo: http://i.imgur.com/ebAxHOO.jpg

Edited by Nytro
Posted

Nytro, ma tem ca te inseli. Nu poti avea complexitate O(n^2) in al 2-lea for, el se repeta de cel mult n ori ( j=i+1;j<n;j++, i >= 0), deci are complexitate O(n).

Cred ca silvian0 are dreptate si complexitatea finala este O(n^2). Ca performanta seamana putin cu selection sort, care are si el complexitate O(n^2). Singura diferenta majora este ca in primul for se parcurge pana la n-1, nu pana la n/2, dar aceasta diferenta nu va afecta complexitatea finala.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...