Created
December 24, 2014 17:57
-
-
Save mockiemockiz/57f648449e707de86b50 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Created by PhpStorm. | |
| * User: mockie | |
| * Date: 12/24/14 | |
| */ | |
| // ================== Data ================================= | |
| $list = ['anto', 'bob', 'boby', 'susi', 'argo', 'sasi', 'szssy', 'bozki']; | |
| // ================== Data ================================= | |
| // ================== First step is sorting the data ================================= | |
| // Sort the data using sorting method, in this case I'm using bubble sort. | |
| // ================== First step is sorting the data ================================= | |
| function bubbleSort($list) | |
| { | |
| $length = count($list)-1; | |
| for ($a=0; $a<$length; $a++) { | |
| for ($b=$a+1;$b<=$length;$b++) { | |
| if ($list[$a] > $list[$b]) { | |
| $first = $list[$a]; | |
| $list[$a] = $list[$b]; | |
| $list[$b] = $first; | |
| } | |
| } | |
| } | |
| return $list; | |
| } | |
| // ================== Second step is indexing the data ================================= | |
| // Index the first character using Btree method for fast searching next time. So we don't need to loop the entire data. | |
| // ================== Second step is indexing the data ================================= | |
| function indexing($list) | |
| { | |
| $temp = ''; | |
| $index = []; | |
| $total = count($list); | |
| for ($a=0; $a<$total; $a++) { | |
| $first = substr($list[$a], 0, 1); | |
| if (!isset($index[$first])) { | |
| $index[$first]['start'] = $a; | |
| $temp = $first; | |
| } | |
| if ($temp != $index[$a]) { | |
| $index[$first]['end'] = $a; | |
| } | |
| } | |
| return $index; | |
| } | |
| $sorting = bubbleSort($list); | |
| $index = indexing($sorting); | |
| // ================== Third step is indexing the data ================================= | |
| // Find the name that we want to search. | |
| // ================== Third step is indexing the data ================================= | |
| function findName($name){ | |
| global $index; | |
| global $sorting; | |
| $firstChar = substr($name, 0, 1); | |
| $start = $index[$firstChar]['start']; | |
| $end = $index[$firstChar]['end']; | |
| for ($a=$start; $a<=$end; $a++) | |
| { | |
| if ($sorting[$a] == $name) { | |
| return $name.' found at '.$a; | |
| break; | |
| } | |
| } | |
| return 'not found'; | |
| } | |
| echo findName('bozki').'<br />'; | |
| echo findName('sasi'); | |
| echo '<hr />'; | |
| echo 'Sorting: <br /><pre>'.print_r($sorting, true).'</pre>'; | |
| echo 'Indexing: <br /><pre>'.print_r($index, true).'</pre>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment