以下代碼有什麼問題?如何使用我的二分查找實現找不到該字母?在C++字符串上進行二進制搜索不起作用
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
#include <cwctype>
using namespace std;
bool contains(string s, char a){
int m = 0;
int n = s.length()-1;
while (m != n) {
int k = (m + n)/2;
if (s[k] == a)
return true;
if (s[k] < a) {
n = k - 1;
} else {
m=k + 1;
}
}
return false;
}
int main() {
string s = "miyvarxarmaiko";
char a = 'm';
if (contains(s,a) == true) {
cout << "s contains character a" << endl;
} else {
cout << "does not contain" << endl;
}
return 0;
}
你爲什麼要對未排序的字符串進行二分搜索?二進制搜索僅適用於已排序的數組。 – 2010-10-05 05:11:04
您可以使用'std :: sort'對字符串和'std :: binary_search'的字符進行排序,以測試某個元素是否在有序範圍內(或者,如果您需要知道元素的位置,則可以使用'std :: lower_bound'和朋友)。 – 2010-10-05 05:20:05