-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathbinary_search.php
79 lines (73 loc) · 2.63 KB
/
binary_search.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
class BinarySearch {
public function __construct($table, $field, $min, $condition = "", $cacheName = "") {
if (empty($cacheName) || $cacheName == "") {
$cacheName = $table;
}
$this->array = apc_fetch($cacheName, $success);
if (!$success) {
echo "$table FROM DATABASE";
if (!empty($condition)) {
echo $query = "select $field from $table where $condition order by $field";
} else {
echo $query = "select $field from $table order by $field";
}
$result = mysql_query($query) or trigger_error(mysql_error(), E_USER_ERROR);
if (mysql_num_rows($result)) {
echo "Sucess";
$this->array = array();
while ($row = mysql_fetch_array($result)) {
$this->array[] = strtolower($row[$field]);
}
apc_store($cacheName, $this->array);
}
}
$this->count = count($this->array);
$this->min = $min;
}
public function search($needle, $max_word = 1) {
$words = explode(' ', $needle);
while ($max_word >= 1) {
if ($max_word == 1) {
foreach ($words as $key => $value) {
if (strlen($value) >= $this->min) {
if ($this->check($value, 0, $this->count - 1)) {
return $value;
}
}
}
} else {
$tot_count = count($words);
for ($i = 0; ($i + $max_word) <= $tot_count; $i++) {
$value = '';
for ($j = $i; $j < ($i + $max_word); $j++) {
$value .= $words[$j] . ' ';
}
$value = trim($value);
//echo "<br> Searched for : " . $value;
if ($this->check($value, 0, $this->count - 1)) {
return $value;
}
}
}
$max_word--;
}
return FALSE;
}
private function check($key, $start, $end) {
if ($start > $end) {
return 0;
} else {
$mid = ((int) (($end - $start) / 2)) + $start;
$comp = strcmp($key, $this->array[$mid]);
if ($comp == 0) {
return $this->array[$mid];
} else if ($comp < 0) {
return $this->check($key, $start, $mid - 1);
} else if ($comp > 0) {
return $this->check($key, $mid + 1, $end);
}
}
}
}
?>