Advertisement
madalinaradu

ASD Pb 21 cautare binara

May 26th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. /** p21 cautare binara*/
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<string.h>
  5. #include<iostream>
  6. using namespace std;
  7.  
  8. int BinarySearch2(string cheie, string a[], int prim, int ultim) {
  9.     if(prim>ultim) {
  10.         return -1;
  11.     }
  12.     int x=(ultim-prim)/3;
  13.     int mij1=prim+x;
  14.     int mij2=prim+2*x/3;
  15.     if(cheie==a[mij1]) {
  16.         return mij1;
  17.     } else {
  18.         if(cheie==a[mij2]) {
  19.             return mij2;
  20.         }
  21.     }
  22.     if(cheie<a[mij1])
  23.         return BinarySearch2(cheie, a,prim, mij1-1);
  24.     if(a[mij1]<cheie && cheie<a[mij2]) {
  25.         return BinarySearch2(cheie, a,mij1+1, mij2-1);
  26.     } else {
  27.         return BinarySearch2(cheie, a, mij2+1, ultim);
  28.     }
  29. }
  30. int FindStringInSortedArray(string cheie, string a[], int n) {///functie wrapper
  31.     return BinarySearch2(cheie,a,0,n-1);
  32. }
  33.  
  34. int main() {
  35.     int n=6;
  36.     string cheie;
  37.     string a[6]= {"a","b","c","d","e","f"};
  38.     cout<<"Dati cheia"<<endl;
  39.     cin>>cheie;
  40.  
  41.     int index=FindStringInSortedArray(cheie,a,6);
  42.     cout<<" Cheia se gaseste pe pozitia:  "<<index;
  43.     return 0;
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement