Skip to content

Instantly share code, notes, and snippets.

@stoimen
Last active August 29, 2015 14:10
Show Gist options
  • Save stoimen/cc5aa136ef8d08d7c1a9 to your computer and use it in GitHub Desktop.
Save stoimen/cc5aa136ef8d08d7c1a9 to your computer and use it in GitHub Desktop.
Linear Search in Sorted Lists
<?php
/**
* Performs a sequential search using sentinel
* and changes the array after the value is found
*
* @param array $arr
* @param mixed $value
*/
function sequential_search(&$arr, $value)
{
$arr[] = $value;
$index = 0;
while ($arr[$index++] != $value);
if ($index < count($arr)) {
// put the item at the front of the list
array_unshift($arr, $arr[$index-1]);
// remove the value from its previous position
unset($arr[$index]);
// unset the sentinel
unset($arr[count($arr)+1]);
return true;
}
return false;
}
// the list
$arr = array(1, 2, 3, 3.14, 5, 4, 6, 9, 8);
// the value
$x = 3.14;
if (sequential_search($arr, $x)) {
// now the array is changed to
// (3.14, 1, 2, 3, 5, 4, 6, 9, 8)
echo "The value $x is found!";
} else {
echo "The value $x doesn't appear to be in the list!";
}
?>
<?php
// list with username/name pairs
$arr = array(
array('name' => 'James Bond', 'username' => 'jamesbond007'),
array('name' => 'John Smith', 'username' => 'jsmith'),
array('name' => 'John Silver', 'username' => 'hohoho'),
array('name' => 'Yoda', 'username' => 'masteryoda900'),
array('name' => 'Darth Vader', 'username' => 'vader'),
);
/**
* Performs a sequential search using a sentinel.
* Returns the index of the item if the item was found
* and FALSE otherwise.
*
* @param array $arr
* @param mixed $value
*/
function sequential_search(&$arr, $value)
{
// usign a sentinel
$arr[] = array('username' => $value, 'name' => '');
$index = 0;
while ($arr[$index++]['username'] != $value);
// if the desired element is in the array
if ($index < count($arr)) {
// push the element at the front of the list
array_unshift($arr, $arr[$index-1]);
// remove the item from its previous place
unset($arr[$index]);
// remove the sentinel
unset($arr[count($arr)]);
// return the index of the value
return $index;
}
// the element has not been found
return FALSE;
}
if (FALSE !== ($iterations = sequential_search($arr, 'vader'))) {
echo "Hello, {$arr[0]['name']}";
echo "Found after $iterations iterations!";
} else {
echo "Hi, guest!";
}
if (FALSE !== ($iterations = sequential_search($arr, 'vader'))) {
echo "Hello, {$arr[0]['name']}";
echo "Found after $iterations iterations!";
} else {
echo "Hi, guest!";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment