0

I have a string array and I am performing a linear and binary search. I understand how the linear search works but for the binary I don't understand this part:

else if (array[mid]<value){
            
            low=mid+1;
        }
        else{
            high=mid-1;
        }

What & how is the comparison between 2 strings happening here: array[mid]<value ?

This is my full code:


#include <iostream>
#include <string.h>
using namespace std;
int linearSearch(string array[],string value);
int binarySearch(string array[],string value);

int main(int argc, const char * argv[]) {
    string array[] = {"apple","banana","ciku","durian","rambutan"};
    string value="banana";
    //using linear search
    int location = linearSearch(array, value);
    cout<<"Location of durian is in:"<<location<<endl;
    //using binary search
    int position = binarySearch(array, value);
    cout<<"Location of durian is in:"<<position<<endl;
    
    
    
}

int binarySearch(string array[],string value){
    int low=0;
    int high=5;
    while(low<=low){
        int mid=(low+high)/2;
        if(array[mid]==value){
            return mid;
        }
        else if (array[mid]<value){
            
            low=mid+1;
        }
        else{
            high=mid-1;
        }
    }
    return -1;
}
int linearSearch(string array[],string value){
    
    
    int arrayLength = 5;
    for(int i=0;i<arrayLength;i++){
        if(array[i]==value){
            
            return i;
            
        }
    }
    return -1;
}

noobaka
  • 37
  • 6

0 Answers0