<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>binary search &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/binary-search/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Balancing a Binary Search Tree</title>
		<link>/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/</link>
		<comments>/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/#comments</comments>
		<pubDate>Tue, 03 Jul 2012 13:30:35 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[B-tree]]></category>
		<category><![CDATA[balanced search tree]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search algorithm]]></category>
		<category><![CDATA[Binary search tree]]></category>
		<category><![CDATA[binary search trees]]></category>
		<category><![CDATA[Binary trees]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Discrete mathematics]]></category>
		<category><![CDATA[Environment]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[NIL]]></category>
		<category><![CDATA[non-balanced binary search]]></category>
		<category><![CDATA[non-balanced search trees]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Scapegoat tree]]></category>
		<category><![CDATA[search tree]]></category>
		<category><![CDATA[Self-balancing binary search tree]]></category>
		<category><![CDATA[Splay tree]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Tree]]></category>

		<guid isPermaLink="false">/?p=3220</guid>
		<description><![CDATA[Introduction The binary search tree is a very useful data structure, where searching can be significantly faster than searching into a linked list. However in some cases searching into a binary tree can be as slow as searching into a linked list and this mainly depends on the input sequence. Indeed in case the input &#8230; <a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Balancing a Binary Search Tree</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/" rel="bookmark" title="Computer Algorithms: Finding the Lowest Common Ancestor">Computer Algorithms: Finding the Lowest Common Ancestor </a></li>
<li><a href="/2012/06/22/computer-algorithms-binary-search-tree-data-structure/" rel="bookmark" title="Computer Algorithms: Binary Search Tree">Computer Algorithms: Binary Search Tree </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>The <a href="/2012/06/22/computer-algorithms-binary-search-tree-data-structure/" title="Computer Algorithms: Binary Search Tree">binary search tree</a> is a very useful data structure, where searching can be significantly faster than searching into a linked list. However in some cases searching into a binary tree can be as slow as searching into a linked list and this mainly depends on the input sequence. Indeed in case the input is sorted the binary tree will seem much like a linked list and the search will be slow. </p>
<figure id="attachment_3244" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/1.-Inserting-into-a-binary-search-tree.png"><img src="/wp-content/uploads/2012/07/1.-Inserting-into-a-binary-search-tree.png" alt="Inserting into a binary search tree" title="Inserting into a binary search tree" width="620" height="399" class="size-full wp-image-3244" srcset="/wp-content/uploads/2012/07/1.-Inserting-into-a-binary-search-tree.png 620w, /wp-content/uploads/2012/07/1.-Inserting-into-a-binary-search-tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">A binary search tree may seem much like a linked lists if the input is nearly sorted!</figcaption></figure>
<p>To overcome this we must change a bit the data structure in order to stay well balanced. It’s intuitively clear that the searching process will be better if the tree is well branched. This is when finding an item will become faster with minimal effort.</p>
<figure id="attachment_3246" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/2.-Balanced-tree.png"><img src="/wp-content/uploads/2012/07/2.-Balanced-tree.png" alt="Balanced tree" title="Balanced tree" width="620" height="399" class="size-full wp-image-3246" srcset="/wp-content/uploads/2012/07/2.-Balanced-tree.png 620w, /wp-content/uploads/2012/07/2.-Balanced-tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Searching into a balanced tree is significantly faster than searching into a non-balanced tree!</figcaption></figure>
<p>Since we know how to construct a binary search tree the only thing left is to keep it balanced. Obviously we will need to re-balance the tree on each insert and delete, which will make this data structure more difficult to maintain compared to non-balanced search trees, but searching into it will be significantly faster.<span id="more-3220"></span></p>
<h2>Overview</h2>
<p>In order to balance a tree we can go for the very basic and intuitive approach. First let’s take a look of one non-balanced tree.</p>
<a href="/wp-content/uploads/2012/07/3.-Balanced-vs.-Non-Balanced.png"><img src="/wp-content/uploads/2012/07/3.-Balanced-vs.-Non-Balanced.png" alt="Balanced vs. Non-Balanced" title="Balanced vs. Non-Balanced" width="620" height="399" class="size-full wp-image-3247" srcset="/wp-content/uploads/2012/07/3.-Balanced-vs.-Non-Balanced.png 620w, /wp-content/uploads/2012/07/3.-Balanced-vs.-Non-Balanced-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a>
<p>Compared to the balanced tree on the right from the image above with the same items we see that the root is approximately equal to its middle item. I.e. 4 is the middle item of the sequence [1,2,3,4,5,6,7]!</p>
<p>If we take a look of the sequence [2 3 4], clearly by building a binary tree it will look like a linked list. However if we choose the middle item for a root &#8211; we’ll easy build a balanced tree. So the only thing to do is to get the middle item out of a list.</p>
<p>We now see that building a balanced binary tree out of a sorted linked list isn’t that difficult. In the other hand, as I said above, on each insert we’ll have to rebalance the tree. You can think of the tree out of the values [1,2,3,4,5] and the same tree after inserting [44,45,46,47,48]. Clearly the root of the resulting tree will no longer be 3. </p>
<p>So we need to implement the re-balancing in three basic operations. First we need to build a linked list out of a balanced binary tree. On the second place we’ll have to find the middle item and on the third place we’ll have to build again a balanced search tree. </p>
<p>Hopefully the first two tasks are easy to implement, because making out a sorted list out of a binary search tree is very easy. We need just to walk through the tree from left-root-right recursively. Because smaller items are in the left sub-tree and greater items are on the right we’re sure that the resulting list will be sorted. Then finding the middle item is as easy as finding the middle index of an array know its length.</p>
<h2>Balancing Optimization</h2>
<p>Of course the main problem of re-balancing a tree on each insert/delete is that this operations will be slow and soon or later we’ll have problems. That can happen if we change often our data structure. That’s why we should think of some optimization. </p>
<p>Normally we insert and re-balance on each step, which is slow. In the other hand we can do bulk insert forgetting about the re-balancing for a while. Only after the inserts are done we can go for re-balancing the entire tree.</p>
<figure id="attachment_3249" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/4.-Bulk-Insert-with-Only-one-Balance.png"><img src="/wp-content/uploads/2012/07/4.-Bulk-Insert-with-Only-one-Balance.png" alt="Bulk Insert with Only one Balance" title="Bulk Insert with Only one Balance" width="620" height="399" class="size-full wp-image-3249" srcset="/wp-content/uploads/2012/07/4.-Bulk-Insert-with-Only-one-Balance.png 620w, /wp-content/uploads/2012/07/4.-Bulk-Insert-with-Only-one-Balance-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Doing bulk insert/delete and only one balancing will make the data structure faster!</figcaption></figure>
<p>The same approach we can use with bulk delete. We can just set to NIL the items we want to delete, but we can keep them in memory for a while. Thus the search will stay relatively fast without rebalancing the tree. However this approach can be used carefully because we’ll keep some data in the memory without actually using it. </p>
<figure id="attachment_3250" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/5.-Bulk-Delete.png"><img src="/wp-content/uploads/2012/07/5.-Bulk-Delete.png" alt="Bulk Delete" title="Bulk Delete" width="620" height="399" class="size-full wp-image-3250" srcset="/wp-content/uploads/2012/07/5.-Bulk-Delete.png 620w, /wp-content/uploads/2012/07/5.-Bulk-Delete-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We can NULL items without actually removing the pointers (links) and the structure of the tree!</figcaption></figure>
<h2>Implementation</h2>
<p>Implementing balanced binary trees is more difficult than just implementing binary search trees. Here’s an example in <a href="/category/php/" title="PHP on stoimen.com">PHP</a>.</p>
<pre lang="PHP">
class Node
{
	protected   $_parent = null;
	protected   $_left = null;
	protected   $_right = null;
	protected   $_key;
    protected   $_data = null;
	
    /**
     * @param int $key
     * @param mixed $data 
     */
	public function __construct($key, $data)
	{
		$this->_key = $key;
        $this->_data = $data;
	}
    
    /**
     * Empty the node by keeping up the key, but
     * setting up the data to NULL 
     */
    public function doEmpty() 
    {
        $this->_data = null;
    }
	
    /**
     * Print the key
     * 
     * @return string
     */
	public function __toString()
	{
		return 'First name: ' . $this->_data['f_name']
                . '<br />'
                . 'Last name: ' . $this->_data['l_name']
                . '<br />' 
                . 'Birthday: ' . $this->_data['b_day'];
	}
    
    public function &getParent() { return $this->_parent; }
    public function setParent($parent) { $this->_parent = $parent; }
    
    public function &getLeft() { return $this->_left; }
    public function setLeft($left) { $this->_left = $left; }
    
    public function &getRight() { return $this->_right; }
    public function setRight($right) { $this->_right = $right; }
    
    public function &getKey() { return $this->_key; }
    public function setKey($key) { $this->_key = $key; }
    
    public function &getData() { return $this->_data; }
    public function setData($data) { $this->_data = $data; }
}

class BalancedBinaryTree
{
    /**
     * Reference to the root tree
     * 
     * @var Node 
     */
	protected $_root = null;
	
    /**
     * @param type $new
     * @param type $node
     * @return type 
     */
	protected function _insert($new, &$root)
	{
        // in case the tree is empty
        // make the new node the root of
        // the tree
		if ($root == null) {
			$root = $new;
			return;
		}
		
		if ($new->getKey() <= $root->getKey()) {
			if ($root->getLeft() == null) {
				$root->setLeft($new);
				$new->setParent($root);
			} else {
				$this->_insert($new, $root->getLeft());
			}
		} else {
			if ($root->getRight() == null) {
				$root->setRight($new);
				$new->setParent($root);
			} else {
				$this->_insert($new, $root->getRight());
			}
		}		
	}
	
    /**
     * FALSE on not found
     * 
     * @param string $firstName
     * @param BalancedBinaryTree $tree
     * @return boolean 
     */
	protected function _search($firstName, &$tree)
	{
        if ($tree == null) {
            return FALSE;
        }

        $data = $tree->getData();
		
        if ($firstName == $data['f_name']) {
			return $tree;
		}
        
        // search the left sub-tree
        return $this->_search($firstName, $tree->getLeft())
                . $this->_search($firstName, $tree->getRight());
	}
    
    /**
     *
     * @param int $key
     * @param Node $tree
     * @return FALSE or Node 
     */
    protected function _searchByKey($key, &$tree)
    {
        if ($tree == null) {
            return FALSE;
        }
        
        if ($tree->getKey() == $key) {
            return $tree;
        } else if ($tree->getKey() > $key) {
            return $this->_searchByKey($key, $tree->getLeft());
        } else {
            return $this->_searchByKey($key, $tree->getRight());
        }
    }
    
    /**
     * Returns a list out of the tree by emptying the tree. 
     * In other way the tree and the list will allocate memory
     * 
     * @param BalancedBinaryTree $tree 
     */
    protected function _leftRootRight($tree)
    {
        if ($tree == null) {
            return array();
        }
        
        return array_merge(
                $this->_leftRootRight($tree->getLeft()),
                array(array('key' => $tree->getKey(), 'data' => $tree->getData())),
                $this->_leftRootRight($tree->getRight()));
    }
    
    public function _balance($list)
    {
        if (empty($list)) {
            return;
        }
        
        // split the list
        $chunks = array_chunk($list, ceil(count($list) / 2));
        $mid = array_pop($chunks[0]);
        
        $node = new Node($mid['key'], $mid['data']);
        $this->insert($node);
        
        $this->_balance($chunks[0]);
        if (isset($chunks[1]))
            $this->_balance($chunks[1]);
    }
    
    /**
     * Balance a binary search tree 
     */
    public function balance()
    {
        $list = array();
        // make a list out of the tree
        $list = $this->_leftRootRight($this->_root);
        
        // find the medium! Because the list is ordered
        // we can find the middle element in various ways
        $chunks = array_chunk($list, ceil(count($list) / 2));
        $mid = array_pop($chunks[0]);
        
        // empty the tree
        $this->_root = null;
        
        // inser the root
        $node = new Node($mid['key'], $mid['data']);
        $this->insert($node);
        
        $this->_balance($chunks[0]);
        $this->_balance($chunks[1]);
    }
	
    /**
     * Insert a new item into the tree
     * 
     * @param type $node 
     */
	public function insert($newNode)
	{
		$this->_insert($newNode, $this->_root);
	}
	
    /**
     * Search by item key
     * 
     * @param int $key
     * @return Node or FALSE
     */
    public function searchByKey($key)
    {
        return $this->_searchByKey($key, $this->_root);
    }
    
    /**
     * @param BalancedBinary $tree
     * @return string 
     */
    protected function _print($tree)
    {
        if ($tree == null) { return ''; }
        
        return $this->_print($tree->getLeft()) . ' ' 
                . $tree->getKey() . ' ' 
                . $this->_print($tree->getRight());
    }
    
    /**
     * Print the tree from left through the root and the right 
     */
    public function __toString()
    {
        if ($this->_root == null) {
            return 'The tree is empty!';
        }

        return $this->_print($this->_root->getLeft()) . ' '
                . $this->_root->getKey() . ' '
                . $this->_print($this->_root->getRight());
    }
}

$a = new Node(90, array(
    'f_name' => 'W.A.',
    'l_name' => 'Mozart',
    'b_day' => '1756-01-27',
));

$b = new Node(100, array(
    'f_name' => 'John',
    'l_name' => 'Smith',
    'b_day' => '23.05.2039',
));

$c = new Node(80, array(
    'f_name' => 'Sarah',
    'l_name' => 'Johnnes',
    'b_day' => 'tomorrow',
));

$d = new Node(60, array(
    'f_name' => 'Ludwig Van',
    'l_name' => 'Beethoven',
    'b_day' => '1770-12-17',
));

$e = new Node(70, array(
    'f_name' => 'Barbara',
    'l_name' => 'Stefanel',
    'b_day' => 'today',
));

$t = new BalancedBinaryTree();

$t->insert($a);
$t->insert($b);
$t->insert($c);
$t->insert($d);
$t->insert($e);

echo $t;

echo $t->searchByKey(70);

$t->balance();

echo $t->searchByKey(70);
</pre>
<h2>Complexity of Searching</h2>
<p>Compared to non-balanced binary search trees we’re sure that searching into a balanced trees is quick enough. The maximum height of the tree is <strong>log(n)</strong> so the worst-case searching is <strong>O(log(n))</strong>.</p>
<figure id="attachment_3238" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/BST-Chart.png"><img src="/wp-content/uploads/2012/06/BST-Chart.png" alt="BST Chart" title="BST Chart" width="600" height="371" class="size-full wp-image-3238" srcset="/wp-content/uploads/2012/06/BST-Chart.png 600w, /wp-content/uploads/2012/06/BST-Chart-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">Compared to searching in linked lists in O(n) time, searching into a balanced binary tree is O(log(n)) in the worst-case scenario!</figcaption></figure>
<h2>Application</h2>
<p>Searching into a balanced binary tree is fast. What is more important is that we&#8217;re sure that in the worst-case scenario the search is O(log(n)). The only problem is that keeping a tree balanced is a slow operation that consumes too much resources and must be performed carefully. </p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/" rel="bookmark" title="Computer Algorithms: Finding the Lowest Common Ancestor">Computer Algorithms: Finding the Lowest Common Ancestor </a></li>
<li><a href="/2012/06/22/computer-algorithms-binary-search-tree-data-structure/" rel="bookmark" title="Computer Algorithms: Binary Search Tree">Computer Algorithms: Binary Search Tree </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Binary Search Tree</title>
		<link>/2012/06/22/computer-algorithms-binary-search-tree-data-structure/</link>
		<comments>/2012/06/22/computer-algorithms-binary-search-tree-data-structure/#comments</comments>
		<pubDate>Fri, 22 Jun 2012 12:35:02 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[B-tree]]></category>
		<category><![CDATA[balanced binary search tree]]></category>
		<category><![CDATA[balanced binary search trees]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search tree]]></category>
		<category><![CDATA[binary search trees]]></category>
		<category><![CDATA[Binary trees]]></category>
		<category><![CDATA[Environment]]></category>
		<category><![CDATA[Extinction]]></category>
		<category><![CDATA[ineffective binary search trees]]></category>
		<category><![CDATA[Linked list]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[R-tree]]></category>
		<category><![CDATA[Red-black tree]]></category>
		<category><![CDATA[Scapegoat tree]]></category>
		<category><![CDATA[search operation]]></category>
		<category><![CDATA[search tree]]></category>
		<category><![CDATA[search trees]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Tree]]></category>

		<guid isPermaLink="false">/?p=3196</guid>
		<description><![CDATA[Introduction Constructing a linked list is a fairly simple task. Linked lists are a linear structure and the items are located one after another, each pointing to its predecessor and its successor. Almost every operation is easy to code in few lines and doesn’t require advanced skills. Operations like insert, delete, etc. over linked lists &#8230; <a href="/2012/06/22/computer-algorithms-binary-search-tree-data-structure/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Binary Search Tree</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/" rel="bookmark" title="Computer Algorithms: Finding the Lowest Common Ancestor">Computer Algorithms: Finding the Lowest Common Ancestor </a></li>
<li><a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" rel="bookmark" title="Computer Algorithms: Balancing a Binary Search Tree">Computer Algorithms: Balancing a Binary Search Tree </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" rel="bookmark" title="Computer Algorithms: Linked List">Computer Algorithms: Linked List </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Constructing a <a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" title="Linked list">linked list</a> is a fairly simple task. Linked lists are a linear structure and the items are located one after another, each pointing to its predecessor and its successor. Almost every operation is easy to code in few lines and doesn’t require advanced skills. Operations like insert, delete, etc. over linked lists are performed in a linear time. Of course on small data sets this works fine, but as the data grows these operations, especially the search operation becomes too slow.</p>
<p>Indeed searching in a linked list has a linear complexity and in the worst case we must go through the entire list in order to find the desired element. The worst case is when the item doesn’t belong to the list and we must check every single item of the list even the last one without success. This approach seems much like the <a href="/2011/11/24/computer-algorithms-sequential-search/" title="the sequential search algorithm">sequential search</a> over arrays. Of course this is bad when we talk about large data sets. </p>
<p><figure id="attachment_3221" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/1.-Search-over-Linked-Lists-and-Arrays.png"><img src="/wp-content/uploads/2012/06/1.-Search-over-Linked-Lists-and-Arrays.png" alt="Search over Linked Lists and Arrays" title="Search over Linked Lists and Arrays" width="620" height="399" class="size-full wp-image-3221" srcset="/wp-content/uploads/2012/06/1.-Search-over-Linked-Lists-and-Arrays.png 620w, /wp-content/uploads/2012/06/1.-Search-over-Linked-Lists-and-Arrays-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Sequential search over arrays seems much like searching in linked lists and it is a basically ineffective opration!</figcaption></figure><span id="more-3196"></span></p>
<p>In terms of arrays, we could perform binary search and go directly in the middle of the array, then jump back or forward. That is because we can access array items directly using their index. However as we saw the linked lists unlike arrays can’t benefit of a direct access and we must go item by item.</p>
<p>Because of this natural problem of linked lists searching is slow and obviously we can’t make it better. The only way to improve searching over dynamic data structures is to use different data structure.</p>
<p>The tree is a data structure where each item, except of keeping some data, keeps a reference (pointer) to its children and its parent.</p>
<figure id="attachment_3223" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/2.-A-tree.png"><img src="/wp-content/uploads/2012/06/2.-A-tree.png" alt="A tree" title="A tree" width="620" height="399" class="size-full wp-image-3223" srcset="/wp-content/uploads/2012/06/2.-A-tree.png 620w, /wp-content/uploads/2012/06/2.-A-tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">A tree data structure. Each item points to its parent and its children. However the root&#8217;s parent it&#8217;s NIL.</figcaption></figure>
<p>Of course if the item doesn’t have children, they are NIL, then this is considered a leaf in the tree terminology. In the other hand if the item doesn’t have parent item it is considered the root.</p>
<figure id="attachment_3226" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/3.-Root-and-Leafs.png"><img src="/wp-content/uploads/2012/06/3.-Root-and-Leafs.png" alt="Root and Leafs" title="Root and Leafs" width="620" height="399" class="size-full wp-image-3226" srcset="/wp-content/uploads/2012/06/3.-Root-and-Leafs.png 620w, /wp-content/uploads/2012/06/3.-Root-and-Leafs-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Root and Leafs</figcaption></figure>
<p>If there is no item in the tree the tree is considered empty. </p>
<p>In these terms only the root has no parent, and each item can have as many children as possible. Here are some trees in form of a diagrams.</p>
<figure id="attachment_3227" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/4.-Trees.png"><img src="/wp-content/uploads/2012/06/4.-Trees.png" alt="Trees" title="Trees" width="620" height="399" class="size-full wp-image-3227" srcset="/wp-content/uploads/2012/06/4.-Trees.png 620w, /wp-content/uploads/2012/06/4.-Trees-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Possible trees</figcaption></figure>
<p>If we’re looking at the root of the tree we can assume there are two sub-trees &#8211; one left and one right. However if we isolate only one of these sub-trees we can again think of it as a tree and assume that it has one left and one right sub-trees and go recursively with this definition.</p>
<figure id="attachment_3228" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/5.-Sub-trees.png"><img src="/wp-content/uploads/2012/06/5.-Sub-trees.png" alt="Sub-trees" title="Sub-trees" width="620" height="399" class="size-full wp-image-3228" srcset="/wp-content/uploads/2012/06/5.-Sub-trees.png 620w, /wp-content/uploads/2012/06/5.-Sub-trees-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Left and right sub-trees</figcaption></figure>
<h2>Overview</h2>
<p>A binary tree is a tree where each item can have at most two children. </p>
<figure id="attachment_3230" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/6.-Binary-Tree.png"><img src="/wp-content/uploads/2012/06/6.-Binary-Tree.png" alt="Binary Tree" title="Binary Tree" width="620" height="399" class="size-full wp-image-3230" srcset="/wp-content/uploads/2012/06/6.-Binary-Tree.png 620w, /wp-content/uploads/2012/06/6.-Binary-Tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In the binary tree each node has at most two sub-trees &#8211; left and right!</figcaption></figure>
<p>Binary trees are especially important because they can contain ordered data in a specific manner. Building a binary tree isn’t difficult at all and it’s very similar to building a linked list.<br />
However a binary tree isn’t more successful in searching than any other tree or data structure. If the items aren’t placed in a specific order we must go through the entire tree in order to find the searched item. This isn’t a great optimization, so we must put an order in it to improve the searching process.</p>
<h3>Binary Search Tree</h3>
<p>The binary search tree is a specific kind of binary tree, where the each item keeps greater elements on the right, while the smaller items are on the left. </p>
<figure id="attachment_3233" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/7.-Binary-search-tree.png"><img src="/wp-content/uploads/2012/06/7.-Binary-search-tree.png" alt="Binary search tree" title="Binary search tree" width="620" height="399" class="size-full wp-image-3233" srcset="/wp-content/uploads/2012/06/7.-Binary-search-tree.png 620w, /wp-content/uploads/2012/06/7.-Binary-search-tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Binary search tree &#8211; BST</figcaption></figure>
<p>Constructing a binary search tree is easy, because we can go for inserting each item only by comparing it with the root and decide where to go (left or right) based on its value. </p>
<figure id="attachment_3234" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/8.-Insert-in-BST.png"><img src="/wp-content/uploads/2012/06/8.-Insert-in-BST.png" alt="Insert in BST" title="Insert in BST" width="620" height="399" class="size-full wp-image-3234" srcset="/wp-content/uploads/2012/06/8.-Insert-in-BST.png 620w, /wp-content/uploads/2012/06/8.-Insert-in-BST-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Inserting in a binary search tree is fairly easy</figcaption></figure>
<h2>Implementation</h2>
<p>The following code in <a href="/category/php/" title="PHP articles in stoimen.com">PHP</a> describes the basic principles of a binary search tree.</p>
<pre lang="PHP">
class Node
{
	public $parent = null;
	public $left = null;
	public $right = null;
	public $data = null;
	
	public function __construct($data)
	{
		$this->data = $data;
	}
	
	public function __toString()
	{
		return $this->data;
	}
}

class BinaryTree
{
	protected $_root = null;
	
	protected function _insert(&$new, &$node)
	{
		if ($node == null) {
			$node = $new;
			return;
		}
		
		if ($new->data <= $node->data) {
			if ($node->left == null) {
				$node->left = $new;
				$new->parent = $node;
			} else {
				$this->_insert($new, $node->left);
			}
		} else {
			if ($node->right == null) {
				$node->right = $new;
				$new->parent = $node;
			} else {
				$this->_insert($new, $node->right);
			}
		}		
	}
	
	protected function _search(&$target, &$node)
	{
		if ($target == $node) {
			return 1;
		} else if ($target->data > $node->data && isset($node->right)) {
			return $this->_search($target, $node->right);
		} else if ($target->data <= $node->data && isset($node->left)) {
			return $this->_search($target, $node->left);
		}
		
		return 0;
	}
	
	public function insert($node)
	{
		$this->_insert($node, $this->_root);
	}
	
	public function search($item) 
	{
		return $this->_search($item, $this->_root);
	}
}

$a = new Node(3);
$b = new Node(2);
$c = new Node(4);
$d = new Node(7);
$e = new Node(6);

$t = new BinaryTree();

$t->insert($a);
$t->insert($b);
$t->insert($c);
$t->insert($d);
$t->insert($e);

echo $t->search($e);
</pre>
<h2>Search Complexity</h2>
<p>Searching in binary search trees is supposed to be faster than searching into linked list. However the searching process in a BST can be very fast, but also can be as slow as on linked list. That is because depending on the input of items they can be placed only on the one side of the root.</p>
<figure id="attachment_3236" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/9.-Tree-or-a-Linked-list.png"><img src="/wp-content/uploads/2012/06/9.-Tree-or-a-Linked-list.png" alt="Tree or a Linked list" title="Tree or a Linked list" width="620" height="399" class="size-full wp-image-3236" srcset="/wp-content/uploads/2012/06/9.-Tree-or-a-Linked-list.png 620w, /wp-content/uploads/2012/06/9.-Tree-or-a-Linked-list-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">By inserting only greater items there are only right sub-trees &#8211; the tree isn&#8217;t different from a linked list and the searching is slow!</figcaption></figure>
<p>That makes the worst-case searching as slow as on linked list which is linear O(n). However if the tree is somehow balanced we can search very quickly with O(log(n)) time.</p>
<a href="/wp-content/uploads/2012/06/BST-Chart.png"><img src="/wp-content/uploads/2012/06/BST-Chart.png" alt="BST Chart" title="BST Chart" width="600" height="371" class="size-full wp-image-3238" srcset="/wp-content/uploads/2012/06/BST-Chart.png 600w, /wp-content/uploads/2012/06/BST-Chart-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a>
<h3>Further Optimization</h3>
<p>We now see how ineffective binary search trees can be, so the only thing we must care is how to keep them balanced, so the search will be faster. The answer is to maintain (during insertion) a balanced binary search tree, which is another very handy data structure. </p>
<p>A balanced binary search tree, or only balanced tree, is a data structure where the height of left and the right sub-trees can vary by one level at most. </p>
<figure id="attachment_3237" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/10.-Balanced-or-not.png"><img src="/wp-content/uploads/2012/06/10.-Balanced-or-not.png" alt="Balanced or not" title="Balanced or not" width="620" height="399" class="size-full wp-image-3237" srcset="/wp-content/uploads/2012/06/10.-Balanced-or-not.png 620w, /wp-content/uploads/2012/06/10.-Balanced-or-not-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Searching in a balanced tree is significantly faster than in some binary search trees!</figcaption></figure>
<h2>Application</h2>
<p>Binary search trees are easy to build and maintain. The great thing is that if the data is well balanced they can be very useful for searching. The only problem is that these structures can be ineffective depending on the insertion order. However if we are somehow sure that the items aren’t ordered on the input, we may expect some optimized searching compared to a linked list. Compared to balanced binary search trees, BST require much less time to build and maintain (insert, delete).</p>
<p>Trees are very useful when working with graphs. Actually one of the very common tasks is walking through the entire tree, which can be done in several ways. First we can go to the left sub-tree, then the root and then the right sub-tree. Or right-root-left. Or root-left-right. </p>
<p>However we can go in depth first often called depth-first-search or a breadth-first-search.</p>
<p>These two methods are designed to walk through the items in a specific order, which is very handy for some specific tasks &#8211; at least each tree is also a graph.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/" rel="bookmark" title="Computer Algorithms: Finding the Lowest Common Ancestor">Computer Algorithms: Finding the Lowest Common Ancestor </a></li>
<li><a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" rel="bookmark" title="Computer Algorithms: Balancing a Binary Search Tree">Computer Algorithms: Balancing a Binary Search Tree </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" rel="bookmark" title="Computer Algorithms: Linked List">Computer Algorithms: Linked List </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/06/22/computer-algorithms-binary-search-tree-data-structure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Insertion Sort</title>
		<link>/2012/02/13/computer-algorithms-insertion-sort/</link>
		<comments>/2012/02/13/computer-algorithms-insertion-sort/#comments</comments>
		<pubDate>Mon, 13 Feb 2012 14:21:57 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Application This algorithm]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[Linear search]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[player]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Selection sort]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Strand sort]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[therefore sorting algorithms]]></category>
		<category><![CDATA[typical algorithm]]></category>

		<guid isPermaLink="false">/?p=2711</guid>
		<description><![CDATA[Overview Sorted data can dramatically change the speed of our program, therefore sorting algorithms are something quite special in computer science. For instance searching in a sorted list is faster than searching in an unordered list. There are two main approaches in sorting &#8211; by comparing the elements and without comparing them. A typical algorithm &#8230; <a href="/2012/02/13/computer-algorithms-insertion-sort/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Insertion Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/03/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2012/02/20/computer-algorithms-bubble-sort/" rel="bookmark" title="Computer Algorithms: Bubble Sort">Computer Algorithms: Bubble Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>Sorted data can dramatically change the speed of our program, therefore sorting algorithms are something quite special in computer science. For instance searching in a sorted list is faster than searching in an unordered list.</p>
<p>There are two main approaches in sorting &#8211; by comparing the elements and without comparing them. A typical algorithm from the first group is insertion sort. This algorithm is very simple and very intuitive to implement, but unfortunately it is not so effective compared to other sorting algorithms as <a href="/2010/06/18/friday-algorithms-iterative-quicksort/" title="Friday Algorithms: Iterative Quicksort">quicksort</a> and merge sort. Indeed insertion sort is useful for small sets of data with no more than about 20 items.</p>
<p>Insertion sort it is very intuitive method of sorting items and we often use it when we play card games. In this case the player often gets an unordered set of playing cards and intuitively starts to sort it. First by taking a card, making some comparisons and then putting the card on the right position.</p>
<p>So let’s say we have an array of data. In the first step the array is unordered, but we can say that it consists of two sub-sets: sorted and unordered, where on the first step the only item in the sorted sub-set is its first item. If the length of the array is n the algorithm is considered completed in n-1 steps. On each step our sorted subset is growing with one item. The thing is that we take the first item from the unordered sub-set and with some comparisons we put it into its place in the sorted sub-set, like on the diagram bellow.</p>
<p><figure id="attachment_2719" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/InsertionSortPrinciple.png"><img src="/wp-content/uploads/2012/02/InsertionSortPrinciple.png" alt="Main principle of insertion sort" title="Principle of Insertion Sort" width="620" class="size-full wp-image-2719" srcset="/wp-content/uploads/2012/02/InsertionSortPrinciple.png 960w, /wp-content/uploads/2012/02/InsertionSortPrinciple-300x107.png 300w" sizes="(max-width: 960px) 100vw, 960px" /></a><figcaption class="wp-caption-text">Main principle of insertion sort.</figcaption></figure><br />
<span id="more-2711"></span><br />
The insertion itself is the tricky part. We can insert the item once we find an item with a smaller value or if we have reached the front of the array like on the diagram bellow.</p>
<figure id="attachment_2721" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/InsertionSort.png"><img src="/wp-content/uploads/2012/02/InsertionSort.png" alt="Insertion sort example" title="Insertion Sort" width="620" class="size-full wp-image-2721" srcset="/wp-content/uploads/2012/02/InsertionSort.png 727w, /wp-content/uploads/2012/02/InsertionSort-300x196.png 300w" sizes="(max-width: 727px) 100vw, 727px" /></a><figcaption class="wp-caption-text">Example of insertion sort</figcaption></figure>
<h2>Implementation</h2>
<p>Here’s a quick implementation of insertion sort in PHP. The good thing is that it is easy to implement, but there are bad news too &#8211; insertion sort is slow and it is ineffective for large data sets.</p>
<pre lang="PHP">
$data = array(4, 2, 4, 1, 2, 6, 8, 19, 3);

function insertion_sort(&$arr)
{
	$len = count($arr);
	
	for ($i = 1; $i < $len; $i++) {
		$tmp = $arr[$i];
		$j = $i;
		
		while (($j >= 0) && ($arr[$j-1] > $tmp)) {
			$arr[$j] = $arr[$j-1];
			$j--;
		}
		$arr[$j] = $tmp;
	}
}
</pre>
<p>We can improve this code a little by using a sentinel, just like the sequential search, in order to remove one of the comparisons.</p>
<pre lang="PHP">
$data = array(4, 2, 4, 1, 2, 6, 8, 19, 3);

function insertion_sort_sentinel(&$arr)
{
	$len = count($arr);
	array_unshift(&$arr, -1);
	
	for ($i = 1; $i < $len+1; $i++) {
		$tmp = $arr[$i];
		$j = $i;
		
		while ($arr[$j-1] > $tmp) {
			$arr[$j] = $arr[$j-1];
			$j--;
		}
		$arr[$j] = $tmp;
	}
	array_shift(&$arr); // remove the sentinel
}
</pre>
<p>Just because we use searching the right position in an ordered array we can use binary search in order to improve even more the algorithm above. Unfortunately this doesn’t improve so much the general efficiency of this algorithm.</p>
<h2>Complexity</h2>
<p>As I said this algorithm is not so effective. Its complexity is O(n<sup>2</sup>) which is far worse than the O(n*log(n)) of quicksort, as you can see on the diagram bellow. </p>
<figure id="attachment_2723" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/InsertionSortComplexityChart.png"><img src="/wp-content/uploads/2012/02/InsertionSortComplexityChart.png" alt="n*n vs. n*log(n)" title="Insertion Sort Complexity Chart" width="600" height="371" class="size-full wp-image-2723" srcset="/wp-content/uploads/2012/02/InsertionSortComplexityChart.png 600w, /wp-content/uploads/2012/02/InsertionSortComplexityChart-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">n*n vs. n*log(n)</figcaption></figure>
<h2>Application</h2>
<p>This algorithm is useful for small sets of data and even if it doesn&#8217;t look like the most effective sorting algorithm, insertion sort can be useful for some reasons. First of all it is easy to implement, but it also does not require additional memory and it can be fast if the data is almost nearly sorted, which is great.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/03/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2012/02/20/computer-algorithms-bubble-sort/" rel="bookmark" title="Computer Algorithms: Bubble Sort">Computer Algorithms: Bubble Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/02/13/computer-algorithms-insertion-sort/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Run-length Encoding</title>
		<link>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/</link>
		<comments>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 09:08:06 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Algorithmic efficiency]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Bzip2]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[data compression algorithm]]></category>
		<category><![CDATA[data compression algorithms]]></category>
		<category><![CDATA[faster services]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[lossless data compression algorithm]]></category>
		<category><![CDATA[Lossy compression]]></category>
		<category><![CDATA[programmer]]></category>
		<category><![CDATA[run-length algorithm]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[This algorithm]]></category>
		<category><![CDATA[virtual machine]]></category>
		<category><![CDATA[web server]]></category>

		<guid isPermaLink="false">/?p=2594</guid>
		<description><![CDATA[Introduction No matter how fast today&#8217;s computers and networks are, the users will constantly need faster and faster services. To reduce the volume of the transferred data we usually use some sort of compression. That is why this computer sciences area will be always interesting to research and develop. There are many data compression algorithms, &#8230; <a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Run-length Encoding</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>No matter how fast today&#8217;s computers and networks are, the users will constantly need faster and faster services. To reduce the volume of the transferred data we usually use some sort of compression. That is why this computer sciences area will be always interesting to research and develop.</p>
<p>There are many data compression algorithms, some of them lossless, others lossy, but their main goal aways will be to spare storage space and traffic. These algorithms are very useful when talking about data transfer between two distant places. Perhaps the best example is the transfer between a web server and a browser.</p>
<p>In the last few years a lot of research has been done on compressing files, executed on the client side. Such files are javascript, css, htmls and images. In fact servers and clients already have some techniques to compress data, like using <a href="http://www.gzip.org/" title="The gzip home page" target="_blank">GZIP</a> for instance, that can dramatically decrease the transfer. In the other hand there are lots of tools and tricks in order to decrease the size of the data.</p>
<p>Actually when a file is executed by the client&#8217;s virtual machine, it doesn&#8217;t matter how &#8220;beautifully&#8221; it is formatted from a programmer&#8217;s point of view. Thus the spaces, tabs and the new lines don&#8217;t bring any significant information for the environment. That is why such compressing tools like <a href="http://developer.yahoo.com/yui/compressor/" title="YUI Compressor" target="_blank">YUI Compressor</a>, <a href="http://code.google.com/closure/compiler/" title="Closure Compiler - Google Code" target="_blank">Google Closure Compiler</a>, etc. remove those symbols. Well, they can achieve even more in order to improve the compression rate. In this post I won&#8217;t cover this, but this shows how important data compression algorithms are.</p>
<p>It would be great if we could just compress data with some tool. Unfortunately this is not the case and usually the compression rate depends on the data itself. It is obvious that the choice of data compression algorithm depends mainly on the data and first of all we must explore the data.</p>
<p>Here I&#8217;ll cover one very simple lossless data compression algorithm called &#8220;run-length encoding&#8221; that can be very useful in some cases.</p>
<figure id="attachment_2618" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/Run-lengthEncoding1.png"><img src="/wp-content/uploads/2012/01/Run-lengthEncoding1.png" alt="Run-length Encoding" title="Run-length Encoding" width="620" class="size-full wp-image-2618" srcset="/wp-content/uploads/2012/01/Run-lengthEncoding1.png 978w, /wp-content/uploads/2012/01/Run-lengthEncoding1-300x129.png 300w" sizes="(max-width: 978px) 100vw, 978px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h2>Overview</h2>
<p>This algorithm consists of replacing large sequences of repeating data with only one item of this data followed by a counter showing how many times this item is repeated. To become clearer let’s see a string example.</p>
<pre lang="PHP">
aaaaaaaaaabbbaxxxxyyyzyx
</pre>
<p>This string&#8217;s length is <strong>24</strong> and as we can see there are lots of repetitions. Using the run-length algorithm, we replace any run with shorter string followed by a counter.</p>
<pre lang="PHP">
a10b3a1x4y3z1y1x1
</pre>
<p>The length of this string is <strong>17</strong>, which is approximately <strong>70%</strong> of the initial length. <span id="more-2594"></span>Obviously this is not the optimal way to compress the given string. For instance we don&#8217;t need to use the digit “1” when the character is repeated only once. In some cases this approach can increase the length of the initial string which is exactly the opposite of what we need. In this case we’ll get the string bellow.</p>
<pre lang="PHP">
a10b3ax4y3zyx
</pre>
<p>Now the length of the resulting string is <strong>13</strong>, which is <strong>54%</strong> of the initial length! A variation of the example above is not to keep a counter of the repetitions of the character, but their position instead. Thus the initial string will be compressed as follows.</p>
<pre lang="PHP">
a0b10a13x14y18z21y22x23
</pre>
<p>Which of these two approaches you&#8217;ll use depends on the goal. In the second case we can achieve a good optimization of <a href="/2011/12/26/computer-algorithms-binary-search/" title="Computer Algorithms: Binary Search">binary search</a>.</p>
<p>It is clear that this algorithm is not only applicable on strings. We can achieve very good results on arrays. A typical example is the transfer of <a href="http://www.json.org/" title="JSON" target="_blank">JSON</a> from a server to a client. Then if there are large sequences of repeating data we can achieve great results.</p>
<h2>Implementation</h2>
<p>The implementation bellow is assuming that we&#8217;re compressing a string and it&#8217;s written on PHP. However the nature of this algorithm doesn&#8217;t restrict us to use only strings. As I said before with slight modifications we can use it with other data structures. It is important only to understand that the run-length algorithm is very useful on large sequences of repeating elements, no matter characters or array items.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = $j = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
			
			if ($i) 
				$output .= $j;
				
			$output .= $msg[$i];
				
			$prev = $msg[$i];
			
			$j = 0;
		}
		$j++;
		$i++;
	}
	
	$output .= $j;
	
	return $output;
}

// a10b3a1x4y3z1y1x1
echo run_length_encode($message);
</pre>
<p>And slightly optimized.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = $j = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
			
			if ($i && $j > 1) 
				$output .= $j;
				
			$output .= $msg[$i];
				
			$prev = $msg[$i];
			
			$j = 0;
		}
		$j++;
		$i++;
	}
	
	if ($j > 1)
		$output .= $j;
	
	return $output;
}

// a10b3ax4y3zyx
echo run_length_encode($message);
</pre>
<p>Finally a small change &#8211; now we store the position of the character.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
				
			$output .= $msg[$i] . $i;
				
			$prev = $msg[$i];
			
		}

		$i++;
	}
	
	return $output;
}

// a0b10a13x14y18z21y22x23
echo run_length_encode($message);
</pre>
<h2>Complexity and Data Compression</h2>
<p>We&#8217;re used to talk about complexity of an algorithm measuring time and we usually try to find the fastest implementation, like in search algorithms. Here it is not so important to compress data quickly, but to compress as much as possible so the output is as small as possible without lossing data. A great feature of run-length encoding is that this algorithm is easy to implement.</p>
<h2>Application</h2>
<p>We can use run-length encoding in many cases. It is commonly used to compress images and is very successful when we deal only with black and white images. Here I&#8217;ll cover another use case that I only mentioned above. Let&#8217;s say we have to transfer a very large array of data to our AJAX-powered application using JSON. Let&#8217;s say also that the data are some years, for instance the years of the premiere of a movie. There are lots of movies with a premiere in the same year, thus although the data is sorted, we actually can&#8217;t have any benefit. More important is that we have large sequences of data. Here we can use run-length encoding.</p>
<pre lang="PHP">
$data = array(
	0 	=> 1991,
	1 	=> 1991,
	...
	2223 	=> 1991,
	2224 	=> 1992,
	...
	19298 	=> 1995,
	19299 	=> 1996,
	...
);
</pre>
<p>As you can see to transfer the whole array can be a nightmare, especially on slow networks. It is better to compress it (i.e. with PHP&#8217;s <a href="http://php.net/manual/en/function.json-encode.php" title="PHP: json_encode" target="_blank">json_encode</a>).</p>
<pre lang="PHP">
// {"0":1991,"1":1991, ..., "2223":1991,"2224":1992, ..., "19298":1995,"19299":1996, ...}
echo json_encode($data);
</pre>
<p>After running run-length encoding we can receive something like the following array (note that these are only sample data and it&#8217;s up to you to decide which is the best format to store data).</p>
<pre lang="PHP">
$data = array(
	0 => array(1991, 2224),
	1 => array(1992, 3948),
	2 => array(1995, 2398),
	3 => array(1996, 3489),
);
</pre>
<p>And the JSON output.</p>
<pre lang="PHP">
// [[1991,2224],[1992,3948],[1995,2398],[1996,3489]]
echo json_encode($data);
</pre>
<p>Note that if the data is sorted we can achieve great success compressing it!!! This approach can be used for images, graphics or map coordinates.</p>
<p>This is only one example of how data compression can be useful in our daily work. Although the communication between the server and the client can be optimized and compressed, we can improve it. In other words we&#8217;re not always sure that the opposite side supports compression.</p>
<p>Well, it&#8217;s true that the client has to decompress the data, which can also be slow. Now in the first case we have only the time to transfer, as on the diagram bellow.</p>
<figure id="attachment_2609" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png"><img src="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png" alt="Data Transfer Without Compression" title="Data Transfer Without Compression" width="620" class="size-full wp-image-2609" srcset="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png 957w, /wp-content/uploads/2012/01/DataTransferWithoutCompression-300x54.png 300w" sizes="(max-width: 957px) 100vw, 957px" /></a><figcaption class="wp-caption-text">Time to transfer data without compression!</figcaption></figure>
<p>In the second case, we should sum the time for compression, transfer and decompression.</p>
<figure id="attachment_2610" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/DataTransferwithCompression.png"><img src="/wp-content/uploads/2012/01/DataTransferwithCompression.png" alt="Data Transfer with Compression" title="Data Transfer with Compression" width="620" class="size-full wp-image-2610" srcset="/wp-content/uploads/2012/01/DataTransferwithCompression.png 953w, /wp-content/uploads/2012/01/DataTransferwithCompression-300x59.png 300w" sizes="(max-width: 953px) 100vw, 953px" /></a><figcaption class="wp-caption-text">Time to send data with compression!</figcaption></figure>
<p>All this is important, but in general data compression can be handy in many cases in our daily work. </p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Interpolation Search</title>
		<link>/2012/01/02/computer-algorithms-interpolation-search/</link>
		<comments>/2012/01/02/computer-algorithms-interpolation-search/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 18:31:42 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search algorithm]]></category>
		<category><![CDATA[Binary search tree]]></category>
		<category><![CDATA[even binary search]]></category>
		<category><![CDATA[Interpolation]]></category>
		<category><![CDATA[Interpolation search]]></category>
		<category><![CDATA[interpolation search algorithm]]></category>
		<category><![CDATA[Jump search]]></category>
		<category><![CDATA[Logarithm]]></category>
		<category><![CDATA[search algorithm]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[searching algorithms]]></category>
		<category><![CDATA[Selection algorithm]]></category>
		<category><![CDATA[Technology/Internet]]></category>

		<guid isPermaLink="false">/?p=2560</guid>
		<description><![CDATA[Overview I wrote about binary search in my previous post, which is indeed one very fast searching algorithm, but in some cases we can achieve even faster results. Such an algorithm is the “interpolation search” &#8211; perhaps the most interesting of all searching algorithms. However we shouldn’t forget that the data must follow some limitations. &#8230; <a href="/2012/01/02/computer-algorithms-interpolation-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Interpolation Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>I wrote about <a title="Computer Algorithms: Binary Search" href="/2011/12/26/computer-algorithms-binary-search/">binary search</a> in my previous post, which is indeed one very fast searching algorithm, but in some cases we can achieve even faster results. Such an algorithm is the “interpolation search” &#8211; perhaps the most interesting of all searching algorithms. However we shouldn’t forget that the data must follow some limitations. In first place the array must be sorted. Also we must know the bounds of the interval.</p>
<p>Why is that? Well, this algorithm tries to follow the way we search a name in a phone book, or a word in the dictionary. We, humans, know in advance that in case the name we’re searching starts with a &#8220;B&#8221;, like &#8220;Bond&#8221; for instance, we should start searching near the beginning of the phone book. Thus if we&#8217;re searching the word “algorithm” in the dictionary, you know that it should be placed somewhere at the beginning. This is because we know the order of the letters, we know the interval (a-z), and somehow we intuitively know that the words are dispersed equally. These facts are enough to realize that the binary search can be a bad choice. Indeed the binary search algorithm divides the list in two equal sub-lists, which is useless if we know in advance that the searched item is somewhere in the beginning or the end of the list. Yes, we can use also <a href="/2011/12/12/computer-algorithms-jump-search/" title="Computer Algorithms: Jump Search">jump search</a> if the item is at the beginning, but not if it is at the end, in that case this algorithm is not so effective.</p>
<p>So the interpolation search is based on some simple facts. The binary search divides the interval on two equal sub-lists, as shown on the image bellow.</p>
<figure id="attachment_2580" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/InterpolationSearchfig.1.png"><img class="size-full wp-image-2580" title="Interpolation Search fig. 1" src="/wp-content/uploads/2012/01/InterpolationSearchfig.1.png" alt="Binary search basic approach" width="620" srcset="/wp-content/uploads/2012/01/InterpolationSearchfig.1.png 959w, /wp-content/uploads/2012/01/InterpolationSearchfig.1-300x79.png 300w" sizes="(max-width: 959px) 100vw, 959px" /></a><figcaption class="wp-caption-text">The binary search algorithm divides the list in two equal sub-lists!</figcaption></figure>
<p>What will happen if we don&#8217;t use the constant ½, but another more accurate constant &#8220;C&#8221;, that can lead us closer to the searched item.</p>
<figure id="attachment_2579" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/InterpolationSearchfig.2.png"><img class="size-full wp-image-2579" title="Interpolation Search fig. 2" src="/wp-content/uploads/2012/01/InterpolationSearchfig.2.png" alt="Interpolation search" width="620" srcset="/wp-content/uploads/2012/01/InterpolationSearchfig.2.png 959w, /wp-content/uploads/2012/01/InterpolationSearchfig.2-300x80.png 300w" sizes="(max-width: 959px) 100vw, 959px" /></a><figcaption class="wp-caption-text">The interpolation search algorithm tries to improve the binary search!</figcaption></figure>
<p><span id="more-2560"></span></p>
<p>The question is how to find this value? Well, we know bounds of the interval and looking closer to the image above we can define the following formula.</p>
<pre lang="PHP">C = (x-L)/(R-L)</pre>
<p>Now we can be sure that we&#8217;re closer to the searched value.</p>
<h2>Implementation</h2>
<p>Here&#8217;s an implementation of interpolation search in PHP.</p>
<pre lang="PHP">$list = array(201, 209, 232, 233, 332, 399, 400);
$x = 332;

function interpolation_search($list, $x)
{
	$l = 0;
	$r = count($list) - 1;

	while ($l <= $r) {
		if ($list[$l] == $list[$r]) {
			if ($list[$l] == $x) {
				return $l;
			} else {
				// not found
				return -1;
			}
		}
		
		$k = ($x - $list[$l])/($list[$r] - $list[$l]);
		
		// not found
		if ($k < 0 || $k > 1) {
			return -1;
		}
		
		$mid = round($l + $k*($r - $l));
		
		if ($x < $list[$mid]) {
			$r = $mid - 1;
		} else if ($x > $list[$mid]) {
			$l = $mid + 1;
		} else {
			// success!
			return $mid;
		}
		
		// not found
		return -1;
	}
}

echo interpolation_search($list, $x);
</pre>
<h2>Complexity</h2>
<p>The complexity of this algorithm is log<sub>2</sub>(log<sub>2</sub>(n)) + 1. While I wont cover its proof, I’ll say that this is very slowly growing function as you can see on the following chart.</p>
<p><a href="/wp-content/uploads/2012/01/logntologlogn.png"><img class="alignnone size-full wp-image-2578" title="log(n) compared to log(log(n))" src="/wp-content/uploads/2012/01/logntologlogn.png" alt="log(n) compared to log(log(n))" width="600" height="371" srcset="/wp-content/uploads/2012/01/logntologlogn.png 600w, /wp-content/uploads/2012/01/logntologlogn-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a></p>
<p>Indeed when the values are equally dispersed into the interval this search algorithm can be extremely useful &#8211; way faster than the binary search. As you can see log<sub>2</sub>(log<sub>2</sub>(100 M)) ≈ 4.73 !!!</p>
<h2>Application</h2>
<p>As I said already this algorithm is extremely interesting and very appropriate in many use cases. Here’s an example where interpolation search can be used. Let’s say there’s an array with user data, sorted by their year of birth. We know in advance that all users are born in the 80’s. In this case sequential or even binary search can be slower than interpolation search.</p>
<pre lang="PHP">$list = array(
	0 => array('year' => 1980, 'name' => 'John Smith', 'username' => 'John'),
	1 => array('year' => 1980, ...),
	...
	10394 => array('year' => 1981, 'name' => 'Tomas M.', ...),
	...
	348489 => array('year' => '1985', 'name' => 'James Bond', ...),
	...
	2808008 => array('year' => '1990', 'name' => 'W.A. Mozart', ...)
);</pre>
<p>Now if we search for somebody born in 1981 a good approach is to use interpolation search.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/02/computer-algorithms-interpolation-search/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Binary Search</title>
		<link>/2011/12/26/computer-algorithms-binary-search/</link>
		<comments>/2011/12/26/computer-algorithms-binary-search/#comments</comments>
		<pubDate>Mon, 26 Dec 2011 13:14:25 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search algorithm]]></category>
		<category><![CDATA[Control flow]]></category>
		<category><![CDATA[famous and best suitable search algorithm]]></category>
		<category><![CDATA[Fibonacci number]]></category>
		<category><![CDATA[Fibonacci search algorithm]]></category>
		<category><![CDATA[Fibonacci search technique]]></category>
		<category><![CDATA[Golden section search]]></category>
		<category><![CDATA[golden section search algorithm]]></category>
		<category><![CDATA[Jump search]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Recursion]]></category>
		<category><![CDATA[Recursion theory]]></category>
		<category><![CDATA[recursive and iterative solution]]></category>
		<category><![CDATA[search algorithm]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[suitable search algorithm]]></category>
		<category><![CDATA[Theoretical computer science]]></category>
		<category><![CDATA[two algorithms]]></category>

		<guid isPermaLink="false">/?p=2538</guid>
		<description><![CDATA[Overview The binary search is perhaps the most famous and best suitable search algorithm for sorted arrays. Indeed when the array is sorted it is useless to check every single item against the desired value. Of course a better approach is to jump straight to the middle item of the array and if the item’s &#8230; <a href="/2011/12/26/computer-algorithms-binary-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Binary Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" rel="bookmark" title="Computer Algorithms: Balancing a Binary Search Tree">Computer Algorithms: Balancing a Binary Search Tree </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>The binary search is perhaps the most famous and best suitable search algorithm for sorted arrays. Indeed when the array is sorted it is useless to check every single item against the desired value. Of course a better approach is to jump straight to the middle item of the array and if the item’s value is greater than the desired one, we can jump back again to the middle of the interval. Thus the new interval is half the size of the initial one.</p>
<figure id="attachment_2561" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/BinarySearchfig.1.png"><img class="size-full wp-image-2561" title="Binary Search fig.1" src="/wp-content/uploads/2011/12/BinarySearchfig.1.png" alt="Binary search basic implementation" width="620" srcset="/wp-content/uploads/2011/12/BinarySearchfig.1.png 959w, /wp-content/uploads/2011/12/BinarySearchfig.1-300x75.png 300w" sizes="(max-width: 959px) 100vw, 959px" /></a><figcaption class="wp-caption-text">Basic implementation of binary search</figcaption></figure>
<p>If the searched value is greater than the one placed at the middle of the sorted array, we can jump forward. Again on each step the considered list is getting half as long as the list on the previous step, as shown on the image bellow.</p>
<figure id="attachment_2564" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/BinarySearchfig.2.png"><img src="/wp-content/uploads/2011/12/BinarySearchfig.2.png" alt="Binary search - basic implementation" title="Binary Search fig.2" width="620" class="size-full wp-image-2564" srcset="/wp-content/uploads/2011/12/BinarySearchfig.2.png 961w, /wp-content/uploads/2011/12/BinarySearchfig.2-300x65.png 300w" sizes="(max-width: 961px) 100vw, 961px" /></a><figcaption class="wp-caption-text">Binary search - basic implementation</figcaption></figure>
<h2>Implementation</h2>
<p>Here’s a sample implementation of this algorithm on <a href="/category/php/" title="PHP on stoimen.com">PHP</a>. Obviously the nature of this approach is guiding us to a recursive implementation, but as we know, sometimes recursion can be dangerous. That&#8217;s why here we can see either the recursive and iterative solution.<span id="more-2538"></span></p>
<h3>Recursive Binary Search</h3>
<pre lang="PHP">
$list = array(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144);
$x = 55;

function binary_search($x, $list, $left, $right) 
{
	if ($left > $right)
		return -1;
	
	$mid = ($left + $right) >> 1;

	if ($list[$mid] == $x) {
		return $mid;
	} elseif ($list[$mid] > $x) {
		return binary_search($x, $list, $left, $mid-1);
	} elseif ($list[$mid] < $x) {
		return binary_search($x, $list, $mid+1, $right);
	}
}

echo binary_search($x, $list, 0, count($list)-1);
</pre>
<h3>Iterative Binary Search</h3>
<pre lang="PHP">
$list = array(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144);
$x = 55;

function iterative_binary_search($x, $list) 
{
	$left = 0;
	$right = count($list)-1;
	
	while ($left <= $right) {
		$mid = ($left + $right) >> 1;
		
		if ($list[$mid] == $x) {
			return $mid;
		} elseif ($list[$mid] > $x) {
			$right = $mid - 1;
		} elseif ($list[$mid] < $x) {
			$left = $mid + 1;
		}
	}
	
	return -1;
}

echo iterative_binary_search($x, $list);
</pre>
<h2>Caution: Optimization</h2>
<p>Most of the optimization techniques mentioned online recommend to replace the expensive operation of dividing by 2 with its bitwise equivalent (n >> 1) == n/2. That is not always true and it is very dependant from the programming language. Thus in PHP those operations are fairly similar as PHP is written in C. You’ve to be aware of the language specific features when optimizing code.</p>
<h2>Fibonacci Search</h2>
<p>Every developer has heard of Fibonacci and his sequence. The Fibonacci search algorithm is practically a variation of the binary search algorithm. In fact the only difference is that the binary search algorithm divides the list into two equal parts, while the Fibonacci search divides it in two but not equal parts. In fact sometimes it is faster to search if you divide the list by such non equal sub-lists. However the length of the sub-lists is not random.</p>
<p>It is clear that the ratio of any two consecutive numbers in the Fibonacci sequence is practically forming the golden ratio. This can lead us to another variation of Fibonacci and binary search - the golden section search. The only different thing is that you’ve to divide the length of the list in two parts exactly by the golden ratio.</p>
<figure id="attachment_2563" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/GoldenRatioSearch.png"><img src="/wp-content/uploads/2011/12/GoldenRatioSearch.png" alt="Golden Section Search" title="Golden Section Search" width="620" class="size-full wp-image-2563" srcset="/wp-content/uploads/2011/12/GoldenRatioSearch.png 960w, /wp-content/uploads/2011/12/GoldenRatioSearch-300x225.png 300w" sizes="(max-width: 960px) 100vw, 960px" /></a><figcaption class="wp-caption-text">The golden section search doesn&#039;t divide the array on two equal sub-lists!</figcaption></figure>
<p>The complexity both of the Fibonacci and the golden section search algorithm is identical with the complexity of the binary search. However these two algorithms are rarely used in practice. Also it is more difficult to implement these two algorithms than the binary search and their advantage depends on specifically dispersed data.</p>
<h2>Complexity</h2>
<p>The complexity of the binary search algorithm is intuitively clear - O(log(n)), which makes it far more effective than the sequential search.</p>
<figure id="attachment_2562" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/chart_1.png"><img src="/wp-content/uploads/2011/12/chart_1.png" alt="log(n)" title="log(n)" width="600" height="371" class="size-full wp-image-2562" srcset="/wp-content/uploads/2011/12/chart_1.png 600w, /wp-content/uploads/2011/12/chart_1-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">f(n) = log(n) compared to f(n) = n</figcaption></figure>
<h2>Application</h2>
<p>It is useless to mention examples of its use. This algorithm is easy to implement and in the same times it is very fast. Yes, indeed, this algorithm is only possible on sorted lists and this is a limitation. Also, as I said, compared to the jump search here we have more than one jump back in most of the cases, which sometimes can be more expensive than jump forward. However is this the fastest search algorithm? I’ll try to answer this question in my next article.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" rel="bookmark" title="Computer Algorithms: Balancing a Binary Search Tree">Computer Algorithms: Balancing a Binary Search Tree </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/12/26/computer-algorithms-binary-search/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Jump Search</title>
		<link>/2011/12/12/computer-algorithms-jump-search/</link>
		<comments>/2011/12/12/computer-algorithms-jump-search/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 09:15:38 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Analysis of algorithms]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search algorithm]]></category>
		<category><![CDATA[Jump search]]></category>
		<category><![CDATA[jump search algorithm]]></category>
		<category><![CDATA[jumping forward]]></category>
		<category><![CDATA[Linear search]]></category>
		<category><![CDATA[primitive jump search]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[Selection algorithm]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[sequential search algorithm]]></category>
		<category><![CDATA[sorting algorithm]]></category>

		<guid isPermaLink="false">/?p=2521</guid>
		<description><![CDATA[Overview In my previous article I discussed how the sequential (linear) search can be used on an ordered lists, but then we were limited by the specific features of the given task. Obviously the sequential search on an ordered list is ineffective, because we consecutively check every one of its elements. Is there any way &#8230; <a href="/2011/12/12/computer-algorithms-jump-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Jump Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>In <a title="Computer Algorithms: Linear Search in Sorted Lists" href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/">my previous article</a> I discussed how the sequential (linear) search can be used on an ordered lists, but then we were limited by the specific features of the given task. Obviously the <a href="/2011/11/24/computer-algorithms-sequential-search/" title="Computer Algorithms: Sequential Search">sequential search</a> on an ordered list is ineffective, because we consecutively check every one of its elements. Is there any way we can optimize this approach? Well, because we know that the list is sorted we can check some of its items, but not all of them. Thus when an item is checked, if it is less than the desired value, we can skip some of the following items of the list by jumping ahead and then check again. Now if the checked element is greater than the desired value, we can be sure that the desired value is hiding somewhere between the previously checked element and the currently checked element. If not, again we can jump ahead. Of course a good approach is to use a fixed step. Let’s say the list length is n and the step’s length is k. Basically we check list(0), then list(k-1), list(2k-1) etc. Once we find the interval where the value might be (m*k-1 &lt; x &lt;= (m+1)*k &#8211; 1), we can perform a sequential search between the last two checked positions. By choosing this approach we avoid a lot the weaknesses of the sequential search algorithm. Many comparisons from the sequential search here are eliminated.</p>
<h2>How to choose the step&#8217;s length</h2>
<p>We know that it is a good practice to use a fixed size step. Actually when the step is 1, the algorithm is the traditional sequential search. The question is what should be the length of the step and is there any relation between the length of the list (n) and the length of the step (k)? Indeed there is such a relation and often you can see sources directly saying that the best length k = √n. Why is that?</p>
<p>Well, in the worst case, we do n/k jumps and if the last checked value is greater than the desired one, we do at most k-1 comparisons more. This means n/k + k &#8211; 1 comparisons. Now the question is for what values of k this function reaches its minimum. For those of you who remember maths classes this can be found with the formula -n/(k^2) + 1 = 0. Now it’s clear that for k = √n the minimum of the function is reached.</p>
<p>Of course you don’t need to prove this every time you use this algorithm. Instead you can directly assign √n to be the step length. However it is good to be familiar with this approach when trying to optimize an algorithm.</p>
<p>Let’s cosider the following list: (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610). Its length is 16. Jump search will find the value of 55 with the following steps.</p>
<figure id="attachment_2539" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/jump-search-fig-1.png"><img class="size-full wp-image-2539" title="jump-search-fig-1" src="/wp-content/uploads/2011/12/jump-search-fig-1.png" alt="Jump search basic implementation" width="620" srcset="/wp-content/uploads/2011/12/jump-search-fig-1.png 964w, /wp-content/uploads/2011/12/jump-search-fig-1-300x65.png 300w" sizes="(max-width: 964px) 100vw, 964px" /></a><figcaption class="wp-caption-text">Jump search skips some of the items of the list in order to improve performance!</figcaption></figure>
<h2>Implementation</h2>
<p>Let’s see an example of jump search, written in <a title="PHP on stoimen.com" href="/category/php/">PHP</a>.<span id="more-2521"></span></p>
<pre lang="PHP">
$list = array();

for ($i = 0; $i < 1000; $i++) {
	$list[] = $i;
}

// now we have a sorted list: (0, 1, 2, 3, ..., 999)

function jump_search($x, $list)
{
	// calculate the step
	$len = count($list);
	$step = floor(sqrt($len));
	$prev = 0;
	
	while ($list[($step < $len ? $step : $len)] < $x) {
		$prev = $step;
		$step += floor(sqrt($len));
		
		if ($step >= $len) {
			return FALSE;
		}
	}
	
	while ($list[$prev] < $x) {
		$prev++;
		if ($prev == ($step < $len ? $step : $len)) {
			return FALSE;
		}
	}
	
	if ($list[$prev] == $x) {
		return $prev;
	}
	
	return FALSE;
}

echo (int)jump_search(674, $list);
</pre>
<p>Here we have a sorted list with 1000 elements that looks like this: (0, 1, 2, ..., 999). Obviously with sequential search we'll find the value of 674 with exactly on the 674-th iteration. Here, with jump search we can reach it on the 44-th iteration, and this shows us the advantage of jump search over the sequential search on ordered lists.</p>
<h2>Further Optimization</h2>
<p>Although all examples here deal with small lists in practice this is not always true. Sometimes the step itself can be a very large number, so once you know the interval where the desired value could be you can perform jump search again.</p>
<p>We saw that the best size of the step is √n, but it is not a good idea to start from the first element of the list just as we didn’t in the example above. A better option is to begin from kth item. Now we can improve the above solution.</p>
<figure id="attachment_2542" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/jump-search-fig-2.png"><img class="size-full wp-image-2542" title="jump-search-fig-2" src="/wp-content/uploads/2011/12/jump-search-fig-2.png" alt="Basic jump search can be slightly optimized!" width="620" srcset="/wp-content/uploads/2011/12/jump-search-fig-2.png 964w, /wp-content/uploads/2011/12/jump-search-fig-2-300x65.png 300w" sizes="(max-width: 964px) 100vw, 964px" /></a><figcaption class="wp-caption-text">The basic implementation of jump search can be slightly optimized!</figcaption></figure>
<h2>Complexity</h2>
<p>Obviously the complexity of the algorithm is O(√n), but once we know the interval where the value is we can improve it by applying jump search again. Indeed let’s say the list length is 1,000,000. The jump interval should be: √1000000=1000. As you can see again, you can use jump search with a new step √1000≈31. Every time we find the desired interval we can apply the jump search algorithm with a smaller step. Of course finally the step will be 1. In this case the complexity of the algorithm is no longer O(√n). Now its complexity is approaching logarithmic value. The problem is that the implementation of this approach is considered to be more difficult than the binary search, where the complexity is also O(log(n)).</p>
<h2>Application</h2>
<p>As almost every algorithm the jump search is very convinient for a certain kind of tasks. Yes, the binary search is easy to implement and its complexity is O(log(n)), but in case of a very large list the direct jump to the middle can be a bad idea. Then we should make a large step back if the searched value is placed at the beginning of the list.</p>
<p>Perhaps every one of us has performed some sort of a primitive jump search in his life without even knowing it. Do you remember cassette recorders? We used the "fast forward" key and periodically checked whether the tape was on our favorite song. Once we stopped at the middle of the song we used the "rewind" button to find exactly the beginning of the song.</p>
<p>This clumsy example can give us the answer of where jump search can be better than binary search. The advantage of jump search is that you need to jump back only once (in case of the basic implementation).</p>
<figure id="attachment_2544" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/jump-search-fig-3.png"><img class="size-full wp-image-2544" title="jump-search-fig-3" src="/wp-content/uploads/2011/12/jump-search-fig-3.png" alt="Jump search is very useful when jumping back is significantly slower than jumping forward!" width="620" srcset="/wp-content/uploads/2011/12/jump-search-fig-3.png 964w, /wp-content/uploads/2011/12/jump-search-fig-3-300x65.png 300w" sizes="(max-width: 964px) 100vw, 964px" /></a><figcaption class="wp-caption-text">Jump search is very useful when jumping back is significantly slower than jumping forward!</figcaption></figure>
<p>If jumping back takes you significantly more time than jumping forward then you should use this algorithm.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/12/12/computer-algorithms-jump-search/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Linear Search in Sorted Lists</title>
		<link>/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/</link>
		<comments>/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/#comments</comments>
		<pubDate>Fri, 02 Dec 2011 14:20:07 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search algorithm]]></category>
		<category><![CDATA[cellular telephone]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[faster algorithm]]></category>
		<category><![CDATA[Index]]></category>
		<category><![CDATA[Linear search]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[sequential search using sentinel]]></category>
		<category><![CDATA[sorting algorithm]]></category>

		<guid isPermaLink="false">/?p=2492</guid>
		<description><![CDATA[Overview The expression &#8220;linear search in sorted lists&#8221; itself sounds strange. Why should we use this algorithm for sorted lists when there are lots of other algorithms that are far more effective? As I mentioned in my previous post the sequential search is very ineffective in most of the cases and it is primary used &#8230; <a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Linear Search in Sorted Lists</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>The expression &#8220;linear search in sorted lists&#8221; itself sounds strange. Why should we use this algorithm for sorted lists when there are lots of other algorithms that are far more effective? As I mentioned in</p>
<p><a href="/2011/11/24/computer-algorithms-sequential-search/" title="Computer Algorithms: Sequential Search">my previous post</a> the sequential search is very ineffective in most of the cases and it is primary used for unordered lists. Indeed sometimes it is more useful first to sort the data and then use a faster algorithm like the binary search. On the other hand the analysis shows that for lists with less than ten items the linear search is much faster than the binary search. Although, for instance, binary search is more effective on sorted lists, sequential search can be a better solution in some specific cases with minor changes. The problem is that when developers hear the expression &#8220;sorted list&#8221; they directly choose an algorithm different from the linear search. Perhaps the problem lays in the way we understand what an ordered list is?</p>
<h3>What is a sorted list?</h3>
<p>We used to think that this list <strong>(1, 1, 2, 3, 5, 8, 13)</strong> is sorted. Actually we think so because it is &#8230; sorted, but the list <strong>(3, 13, 1, 3, 3.14, 1.5, -1)</strong> is also sorted, except that we don’t know how. Thus we can think that any array is sorted, although it is not always obvious how. There are basically two cases when sequential search can be very useful. First when the list is very short or when we know in advance that there are some values that are very frequently searched.<span id="more-2492"></span> Let&#8217;s say we have a very large list, with hundreds of thousands of items, but actually most of the searches in that list always find the same ten values. This additional information tells us that using a binary search will be quite ineffective in this case. A possible approach, of course, is to place those values at the front of the list and to perform a sequential search. <figure id="attachment_2523" style="width: 620px" class="wp-caption alignnone"></p>
<p><a href="/wp-content/uploads/2011/12/search.jpg"><img src="/wp-content/uploads/2011/12/search.jpg" alt="You should choose a search algorithm by carefully examining the data you search." title="magnifying glass" width="620" height="270" class="size-full wp-image-2523" srcset="/wp-content/uploads/2011/12/search.jpg 620w, /wp-content/uploads/2011/12/search-300x130.jpg 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">You should choose a search algorithm by carefully examining the data you search.</figcaption></figure> Unfortunately the search will be slow when we search for some value missing from the front of the list, but then we can use another algorithm on sorted lists. Still there is one question that should be answered. We do know that in most of the cases we search for the same values, but we do not know exactly those values. So the question is how to put the most frequently accessed values at the front of the list, since we don&#8217;t know them. Here we need some sort of auto adjustment of the list.</p>
<h2>Self-Organization</h2>
<p>Self-organization practically means that every time we search and find the desired value, we somehow change the list so the next search will be far more effective. There are basically two approaches to do that.</p>
<ol>
<li>To move the item one position forward to the front of the list;</li>
<li>To move the item directly at the front of the list; </li>
</ol>
<p>Of course it depends on your case which approach you&#8217;ll choose, but it is assumed that the second option, the one that we choose to move the item directly at the front of the list, is better. Indeed if we choose the first option and the list is (&#8230;, 24, 31) after constantly searching for those two values the array will be changing from (&#8230;, 24, 31) to (&#8230;, 31, 24) and once again to (&#8230;, 24, 31) and so on and so on. Thus a better solution is to move the desired item directly to the front of the list. Now if we look for the value of &#8220;5&#8221; in the list</p>
<p><strong>(1, 2, 4, &#8230;, 5, &#8230;, 398)</strong> it will become <strong>(5, 1, 2, &#8230;, 398)</strong> after the value is found. By choosing this approach we can be sure that as the number of searches increases, the most frequently searched values are placed at the front of the list. Now the sequential search is quite a good solution! Here&#8217;s an example of sequential search from my previous article. The only change is that after we find the desired value we need to move it to the front of the list.</p>
<p><script src="https://gist.github.com/stoimen/cc5aa136ef8d08d7c1a9.js?file=linear_search.php"></script></p>
<h2>Application</h2>
<p>Using sequential search in sorted lists can be very useful and fast, the only thing is that we need to know in advance that there are some values that are frequently searched. A typical example of this case is the contact list on your phone. Perhaps you have lots of names in there, but most of the times you search in it is to find your best friends&#8217; and family phone numbers. That is why most of the cell phone manufacturers add to their phones the ability to predefine shortcut keys for the most frequently dialed numbers. Here&#8217;s another use case. Let&#8217;s say that we have the same scenario as in my previous</p>
<p><a href="/2011/11/24/computer-algorithms-sequential-search/" title="Computer Algorithms: Sequential Search">post</a>, where username/name pairs are stored into a CSV file. We can fetch those values in a PHP array.</p>
<p>Every time a user enters the site we search for his name by his username and a welcome message is displayed. We know that some users enter the site very frequently while others do that once per month so we cannot only perform a sequential search but also we can use self-organization for the array and change the CSV file at the end.</p>
<p><script src="https://gist.github.com/stoimen/cc5aa136ef8d08d7c1a9.js?file=linear_search_v1.php"></script><br />
The result is:</p>
<pre><code>Hello, Darth Vader 
Found after 5 iterations!
Hello, Darth Vader
Found after 1 iterations!
</code></pre>
<p>Now every time Darth Vader tries to sign in, you won&#8217;t bother him to wait a lot for sure. However I bet nobody uses CSV files to store such information, but this is only an example.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Sequential Search</title>
		<link>/2011/11/24/computer-algorithms-sequential-search/</link>
		<comments>/2011/11/24/computer-algorithms-sequential-search/#comments</comments>
		<pubDate>Thu, 24 Nov 2011 09:25:35 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search algorithm]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[consecutive search]]></category>
		<category><![CDATA[forward sequential search]]></category>
		<category><![CDATA[Index]]></category>
		<category><![CDATA[ineffective searching algorithm]]></category>
		<category><![CDATA[ineffective searching algorithms]]></category>
		<category><![CDATA[Linear search]]></category>
		<category><![CDATA[linear search algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[reverse linear search approach]]></category>
		<category><![CDATA[search algorithm]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[sequential search]]></category>

		<guid isPermaLink="false">/?p=2483</guid>
		<description><![CDATA[Overview This is the easiest to implement and the most frequently used search algorithm in practice. Unfortunately the sequential search is also the most ineffective searching algorithm. However, it is so commonly used that it is appropriate to consider several ways to optimize it. In general the sequential search, also called linear search, is the &#8230; <a href="/2011/11/24/computer-algorithms-sequential-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Sequential Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>This is the easiest to implement and the most frequently used search algorithm in practice. Unfortunately the sequential search is also the most ineffective searching algorithm. However, it is so commonly used that it is appropriate to consider several ways to optimize it. In general the sequential search, also called linear search, is the method of consecutively check every value in a list until we find the desired one.</p>
<h2>Basic Implementation</h2>
<p>The most natural approach is to loop through the list until we find the desired value. Here’s an implementation on PHP using FOR loop, something that can be easily written into any other computer language.</p>
<p><script src="https://gist.github.com/stoimen/cdc433af43d3f396fd2b.js"></script></p>
<p>This is really the most ineffective implementation. There are two big mistakes in this code. First of all we calculate the length of the list on every iteration of the array, and secondly after we find the desired element, we don’t break the loop, but continue to loop through the array.</p>
<p><img src="/wp-content/uploads/2011/11/forward-linear-search.jpg" alt="Forward Linear Search" /></p>
<p>Yes, if the element is repeated without the “break” we can find its last occurrence, but if not the loop will iterate over the end of the array with no practical value.</p>
<h3>Optimization of the forward sequential search</h3>
<p><script src="https://gist.github.com/stoimen/94ec4473ac050fb0fedf.js"></script></p>
<p>&#8230; and javascript:</p>
<p><script src="https://gist.github.com/stoimen/21f1496da3488e2c8c9c.js"></script></p>
<p><img src="/wp-content/uploads/2011/11/optimized-forward-linear-search.jpg" alt="Optimized forward linear search" /></p>
<p>Even with this little optimization the algorithm remains ineffective. As we can see, on every iteration we have two conditional expressions. First we check whether we’ve reached the end of the list, and then we check whether the current element equals to the searched element. So the question is can we reduce the number of the conditional expressions?</p>
<h2>Searching in reverse order</h2>
<p>Yes, we can reduce the number of comparison instructions from the forward approach of the linear search algorithm by using reverse order searching. Although it seems to be pretty much the same by reversing the order of the search we can discard one of the conditional expressions.</p>
<p><script src="https://gist.github.com/stoimen/02c44ea1d8238d5f39dc.js?file=sequential_search_reverse.php"></script></p>
<p><em>Note that we need to adjust index because of $index—expression.</em></p>
<p>Indeed here we have only one conditional expression, but the problem is that this implementation is correct ONLY when the element exists in the list, which is not always true. If the element doesn’t appears into the list, then this code can lead to an infinite loop. OK, but how can we stop the loop even when the list doesn’t contain the desired value? The answer is, by adding the searched value to the list.</p>
<h2>Sentinel</h2>
<p>The above problem can be solved by inserting the desired item as a sentinel value. Thus we’re sure that the list contains the value, so the loop will stop for sure even if at the beginning the value didn’t appear to be part of the list.</p>
<p><img src="/wp-content/uploads/2011/11/sentinel-linear-search.jpg" alt="Using setinel in sequential search" /></p>
<p><script src="https://gist.github.com/stoimen/02c44ea1d8238d5f39dc.js?file=sequential_search_sentinel.php"></script></p>
<p>This approach can be used to overcome the problem of the reverse linear search approach from the previous section.</p>
<h2>Complexity</h2>
<p>As I said at the beginning of this post this is one of the most ineffective searching algorithms. Of course the best case is when the searched value is at the very beginning of the list. Thus on the first comparison we can find it. On the other hand the worst case is when the element is located at the very end of the list. Assuming that we don’t know where the element is and the possibility to be anywhere in the list is absolutely equal, then the complexity of this algorithm is O(n).</p>
<h3>Different cases</h3>
<p>We must remember, however, that the algorithm’s complexity can vary depending on whether the element occurs once.</p>
<h3>Is it so ineffective?</h3>
<p>Sequential search can be very slow compared to binary search on an ordered list. But actually this is not quite true. <strong>Sequential search can be faster than binary search</strong> for small arrays, but it is assumed that for n &lt; 8 the sequential search is faster.</p>
<h2>Application</h2>
<p>The linear search is really very simple to implement and most web developers go to the forward implementation, which is the most ineffective one. On the other hand this algorithm is quite useful when we search in an unordered list. Yes, searching in an ordered list is something that can dramatically change the search algorithm. Actually searching and sorting algorithms are often used together.</p>
<p>A typical case is pulling something from a database, usually in form of a list and then search for some value in it. Unfortunately in most of the cases the database orders the returned result set and yet most of the developers perform a consecutive search over the list. Yet again when the list is ordered it is better to use binary search instead of sequential search.<br />
Let’s say we have a CSV file containing the usernames and the names of our users.</p>
<pre><code>Username,Name
jamesbond007,James Bond
jsmith,John Smith
...
</code></pre>
<p>Now we fetch these values into an array.</p>
<pre><code>// work case
$arr = array(
    array('name' =&amp;gt; 'James Bond', 'username' =&amp;gt; 'jamesbond007'),
    array('name' =&amp;gt; 'John Smith', 'username' =&amp;gt; 'jsmith')
);
</code></pre>
<p>Now using sequential search &#8230;</p>
<pre><code>// using a sentinel
$x = 'jsmith';
$arr[] = array('username' =&amp;gt; $x, 'name' =&amp;gt; '');
$index = 0;

while ($arr[$index++]['username'] != $x);

if ($index &amp;lt; count($arr)) {
    echo "Hello, {$arr[$index-1]['name']}";
} else {
    echo "Hi, guest!";
}
</code></pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/11/24/computer-algorithms-sequential-search/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
