By sorting the data, you spend time up front, betting it will pay off when you need to search. But even this searching costs something. A binary search may take several steps. When you need to do hundreds of searches, you may look for further improvement in performance. One way is to perform every possible search beforehand, creating an index. A lot of work is done at first, which allows searches to be performed fast.
Let's explore how we can transform the binary search into a single lookup. We want an array that, given a name, returns its position in the
A Binary Search
original array. Our list of employees has two people with the same name, so we'll have to build a list of matches. We won't bother sorting the list. It won't help, because we will be visiting every element of the array. As we visit each element, we create a new array. The index of this array is the name of the employee. Each element of the index will be an array of indices in the employee array. Once the index is created, finding an employee is a single statement. If the name is found in the array, we can retrieve the index values for the employee array.
This example is not very realistic because we're only making one search, and we're building the index with each request. The index needs to be built only once, as long as the employee array doesn't change. You could save the array to a file, perhaps using PHP serialization functionality, and then load it when needed. I wrote similar code for the FreeTrade project that indexes keywords that appear in pages of a Web site.
Of course, databases present a larger solution to managing data. In most cases, it's best to rely on a database to store large amounts of data, because databases have specialized code for searching and sorting.
PHP Related Interview Questions
|PHP Interview Questions||MySQL Interview Questions|
|PHP+MySQL Interview Questions||Drupal Interview Questions|
|MYSQL DBA Interview Questions||PHP5 Interview Questions|
|WordPress Interview Questions||Joomla Interview Questions|
|CakePHP Interview Questions||CodeIgniter Interview Questions|
|PHP7 Interview Questions|
An Introduction To Php
Variables, Operators, And Expressions
Classes And Objects
I/o And Disk Access
Time, Date, And Configuration Functions
Parsing And String Evaluation
Sorting Searching And Random Numbers
Integration With Html
Efficiency And Debugging
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.