task5

mail@pastecode.io avatar
unknown
c_cpp
7 months ago
1.4 kB
2
Indexable
Never
#include <iostream>
#include <string>
using namespace std;


int linearSearch(string array[], string x, int size) {
    int index = -1;
    for(int i = 0; i < size; i++) {
        if(array[i] == x) {
            index = i;
        }
    }
    return index;
}

int binarySearch(string array[], string x, int size) {
    
    int low = 0;
    int high = size-1;
    
    while(low <= high) {
        int mid = low + (high - low) / 2;
        string nameAtMid = array[mid];
        
        if(nameAtMid == x) {
            return mid;
        }
        else if(nameAtMid[0] < x[0]) { // A-E < F-H == 1
            low = mid+1;
        }
        
        else if(nameAtMid[0] > x[0]) { // A-E > F-H == 1
            high = mid-1;
        }
        
        else {
            return -1;
        }
    }
    
}


int main() {
  string names[]= {"Alfred","Buck","Cassandra", "Dorothy","Erhmantraut", "Fredrich", "Gustavo", "Harris"};
  
  
  int size = sizeof(names) / sizeof(names[0]);
  
  string ud_name;
  
  cout << "Enter the name of in formal case" << endl;
  cin >> ud_name;
  
  cout << endl;
  int res = binarySearch(names,ud_name,size); 
  // change res = linearSearch(names,ud_name,size); for linear search
  if(res!=-1) {
      cout << "name found at: " << res << endl;
  }
  
  else {
      cout << "not found, make sure case is formal." << endl;
  }
}