c++ - Search for first index of 'xy' in string using divide and conquer -


i have find first instance of sub string "xy" in char array, using divide , conquer split array half (so array[0...mid] , array[mid+1...size] mid = size+1/2) , recursively running algorithm on both halves. substring 'xy' in left half, in right half, or between 2 halves. returns index of 'x' if first 'xy' found, otherwise returns -1. method allowed 2 parameters, (pointer to) array , size of array. tried using modified binary search, , code follows:

(ps. pseudocode resembles c++, doesn't have proper logic has good)

public int xy-search(char* data, int n){ //starts @ l=0 , r == n-1      int l = 0; //left index      int r = n-1; // right index      if (n==1)         return -1;      if (l>r) // not found         return -1;      int mid = l+r/2; //get mid point      if (data[mid] == ‘x’ && data[mid+1] == ‘y’)         return mid;      else if (l==r) // not found         return -1;      else {         int left = xy-search(data, left); //check left          int right = xy-search(data+left+1, n - left - 1); // check right          if (left != -1) //if found @ left, return index             return left;          if (right != -1) //if found @ right, return index             return right;          else              return -1;     }   } 

i need check work , tell me if going wrong. also, feel there should condition checks left first , if fails, right, looking first instance of 'xy'.

i don't know why want use divide , concur. way. data might large , want use multi thread , on.... think can use this:

int xy_find(string str , int start , int end) {     int min = (start + end) / 2;     if (str.substr(start,2) == "xy")     {         return start;     }     if (end - start <= 2)     {         return -1 ;     }     else      {         int leftpos = xy_find(str , start , min + 1);         if (leftpos != -1)         {             return leftpos;         }         int rightpos = xy_find(str , min , end);         if (rightpos != -1)         {             return rightpos;         }     }     return -1; } 

there 1 thing, divided tow parts. have 1 common character if "xy" @ mid wont work wrong.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -