Computer Science, asked by srushti384, 10 months ago


using binary search method in c++ language search a character from the given string .

Answers

Answered by piyushnehra2006
1

Answer:

Give the string also

I hope it helps you

plz mark me as brainliest and follow me.....

Answered by seemakumarib65
0

Answer:

GEEKSFORGEEKS

Binary Search a String

Given a sorted array of String and a String x, find index of x if it is present in the array.

Examples:

Input : arr[] = { "contribute", "geeks", "ide", "practice"}, x = "ide"

Output : 2

The String x is present at index 2.

Input : arr[] = { "contribute", "geeks", "ide", "practice"}, x = "zz"

Output : -1

The String "zz" is not present.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Prerequisites : Binary Search, String Comparison in Java

The idea is to compare x with middle string in the given array. If it matches, then return mid, else if it is smaller than mid, then search in left half, else search in right half.

// CPP program to implement Binary Search for strings

#include<bits/stdc++.h>

using namespace std;

// Returns index of x if it is present in arr[],

// else return -1

int binarySearch(string arr[], string x,int n)

{

int l = 0 ;

int r = n - 1;

while (l <= r)

{

int m = l + (r - l) / 2;

int res;

if (x == (arr[m]))

res = 0;

// Check if x is present at mid

if (res == 0)

return m;

// If x greater, ignore left half

if (x > (arr[m]))

l = m + 1;

// If x is smaller, ignore right half

else

r = m - 1;

}

return -1;

}

// Driver code

int main()

{

string arr[] = { "contribute", "geeks", "ide", "practice"};

string x = "ide";

int n = 4;

int result = binarySearch(arr, x,n);

if (result == -1)

cout << ("Element not present");

else

cout << ("Element found at index ") << result;

}

//

Similar questions