Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 2

Metoda de programare Divide et Impera

- Se aplica pb. care permit impartirea in mod repetat in 2 sau mai multe subpb. de acelasi tip pana se
ajunge la pb. cu rezolvare evidenta. Sol. pb. initiale se obtine pe baza solutiilor subproblemelor pe care
le-am rezolvat anterior.

Suma elementelor unui vector

ITERATIVA:

int Suma(int a[], int n) {

int i, s=0;

for(i=1;i<=n;++i) s=+a[i];

return s;

RECURSIVA:

int Suma(int a[], int n){

if(n==1) return a[1];

else return a[n]+Suma(a, n-1);

DIVIDE et IMPERA:

int Suma(a[], int s, int d){

if(s==d) return a[s];

else{

int mij=(s+d)/2;

int S1=Suma(a, s, mij);

int S2=Suma(a, mij+1, d);

return S1+S2;

}
Cautare binara

int CB(int a[], int x, int s, int d) {

if(s<d) return 0;

else{

int mij=(s+d)/2;

if(x==a[mij]) return 1;

else if(x<a[mij]) return CB(a, x, s, mij-1);

else return CB(a, x, mij+1, d);

Suma elem. matrici

int S(int a[], int l1, int c1, int l2, int c2){

if(l1==l2&&c1==c2) return a[l1][c1];

else{

int lm=(l1+l2)/2;

int cm=(c1+c2)/2;

int S1=Suma(a, l1, c1, lm, cm);

int S2=Suma(a, l1, cm+1, lm, c2);

int S3=Suma(a, lm+1, c1, l2, cm);

int S4=Suma(a, lm+1, cm+1, l2, c2);

return S1+S2+S3+S4;

You might also like