<?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>Technology/Internet &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/technologyinternet/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: Kruskal&#8217;s Minimum Spanning Tree</title>
		<link>/2012/11/12/computer-algorithms-kruskals-minimum-spanning-tree/</link>
		<comments>/2012/11/12/computer-algorithms-kruskals-minimum-spanning-tree/#comments</comments>
		<pubDate>Mon, 12 Nov 2012 12:01:47 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Bridge]]></category>
		<category><![CDATA[Distributed minimum spanning tree]]></category>
		<category><![CDATA[Environment]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[Joseph Kruskal]]></category>
		<category><![CDATA[Kruskal's algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Minimum spanning tree]]></category>
		<category><![CDATA[minimum spanning tree algorithms]]></category>
		<category><![CDATA[Prim's algorithm]]></category>
		<category><![CDATA[Reverse-delete algorithm]]></category>
		<category><![CDATA[Spanning tree]]></category>
		<category><![CDATA[statistician]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[The algorithm]]></category>
		<category><![CDATA[Theoretical computer science]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[two main algorithms]]></category>

		<guid isPermaLink="false">/?p=3439</guid>
		<description><![CDATA[Introduction One of the two main algorithms in finding the minimum spanning tree algorithms is the algorithm of Kruskal. Before getting into the details, let’s get back to the principles of the minimum spanning tree. We have a weighted graph and of all spanning trees we’d like to find the one with minimal weight. As &#8230; <a href="/2012/11/12/computer-algorithms-kruskals-minimum-spanning-tree/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Kruskal&#8217;s Minimum Spanning Tree</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/11/19/computer-algorithms-prims-minimum-spanning-tree/" rel="bookmark" title="Computer Algorithms: Prim&#8217;s Minimum Spanning Tree">Computer Algorithms: Prim&#8217;s Minimum Spanning Tree </a></li>
<li><a href="/2012/11/05/computer-algorithms-minimum-spanning-tree/" rel="bookmark" title="Computer Algorithms: Minimum Spanning Tree">Computer Algorithms: Minimum Spanning Tree </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="/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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>One of the two main algorithms in <a href="/2012/11/05/computer-algorithms-minimum-spanning-tree/" title="Computer Algorithms: Minimum Spanning Tree">finding the minimum spanning tree</a> algorithms is the algorithm of Kruskal. Before getting into the details, let’s get back to the principles of the minimum spanning tree. </p>
<p>We have a weighted graph and of all spanning trees we’d like to find the one with minimal weight. As an example on the picture above you see a spanning tree (T) on the graph (G), but that isn&#8217;t the minimum weight spanning tree!</p>
<p><figure id="attachment_3459" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/11/1.-A-graph-and-a-possible-spanning-tree.png"><img src="/wp-content/uploads/2012/11/1.-A-graph-and-a-possible-spanning-tree.png" alt="A graph and a possible spanning tree" title="A graph and a possible spanning tree" width="620" height="399" class="size-full wp-image-3459" srcset="/wp-content/uploads/2012/11/1.-A-graph-and-a-possible-spanning-tree.png 620w, /wp-content/uploads/2012/11/1.-A-graph-and-a-possible-spanning-tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure><span id="more-3439"></span></p>
<p>We can think of a group of islands and the possible connections of bridges connecting them. Of course building bridges is expensive and time consuming, so we must be aware of what kind of bridges we want to build. Nevertheless there is an important question, what’s the minimum price we’d like to pay to build such set of bridges connecting all the islands. </p>
<figure id="attachment_3457" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/11/2.-Islands-and-bridges.png"><img src="/wp-content/uploads/2012/11/2.-Islands-and-bridges.png" alt="Islands and bridges" title="Islands and bridges" width="620" height="399" class="size-full wp-image-3457" srcset="/wp-content/uploads/2012/11/2.-Islands-and-bridges.png 620w, /wp-content/uploads/2012/11/2.-Islands-and-bridges-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Thus we practically need to build a minimum spanning tree, where the vertices will be the islands, while the edges will be the possible bridges between them. Every possible bridge has a weight (the price or the time we need to build it, etc.).</p>
<p>This scenario is only one of possible use cases of where minimum spanning trees can be used in practice.  </p>
<p>The two main approaches – the Kruskal’s and the Prim’s algorithms however differ. </p>
<h2>Overview</h2>
<p>The algorithm of Kruskal starts by initializing a set of |V| trees. </p>
<figure id="attachment_3458" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/11/3.-A-set-of-V-trees.png"><img src="/wp-content/uploads/2012/11/3.-A-set-of-V-trees.png" alt="A set of V trees" title="A set of V trees" width="620" height="399" class="size-full wp-image-3458" srcset="/wp-content/uploads/2012/11/3.-A-set-of-V-trees.png 620w, /wp-content/uploads/2012/11/3.-A-set-of-V-trees-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>During the process of building the final spanning tree we keep a forest. Obviously we start with a forest with |V| trees, where each tree is a single node tree.</p>
<figure id="attachment_3456" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/11/4.-A-single-node-tree.png"><img src="/wp-content/uploads/2012/11/4.-A-single-node-tree.png" alt="A single node tree" title="A single node tree" width="620" height="399" class="size-full wp-image-3456" srcset="/wp-content/uploads/2012/11/4.-A-single-node-tree.png 620w, /wp-content/uploads/2012/11/4.-A-single-node-tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>On some point we have a forest of “k” trees which are all a sub-trees of the minimum spanning tree. </p>
<figure id="attachment_3455" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/11/5.-A-forest-out-of-K-sub-trees.png"><img src="/wp-content/uploads/2012/11/5.-A-forest-out-of-K-sub-trees.png" alt="Growing forest" title="Growing forest" width="620" height="399" class="size-full wp-image-3455" srcset="/wp-content/uploads/2012/11/5.-A-forest-out-of-K-sub-trees.png 620w, /wp-content/uploads/2012/11/5.-A-forest-out-of-K-sub-trees-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Finally one step before building the final MST we have two trees and we connect them with the less weighted edge left that connects them.</p>
<p>It’s important to note that during the process of building the tree we sort the edges in ascending order by their weight.</p>
<figure id="attachment_3454" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/11/6.-Sorted-Edges.png"><img src="/wp-content/uploads/2012/11/6.-Sorted-Edges.png" alt="Sorted edges" title="Sorted edges" width="620" height="399" class="size-full wp-image-3454" srcset="/wp-content/uploads/2012/11/6.-Sorted-Edges.png 620w, /wp-content/uploads/2012/11/6.-Sorted-Edges-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Than we start getting edges and check whether their ends (the two vertices making the edge) belong to a different sub-trees.</p>
<figure id="attachment_3453" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/11/7.-Check-edges.png"><img src="/wp-content/uploads/2012/11/7.-Check-edges.png" alt="Check edges" title="Check edges" width="620" height="399" class="size-full wp-image-3453" srcset="/wp-content/uploads/2012/11/7.-Check-edges.png 620w, /wp-content/uploads/2012/11/7.-Check-edges-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<h2>Pseudo Code</h2>
<pre>
1. T (the final spanning tree) is defined to be the empty set;
2. For each vertex v of G, make the empty set out of v;
3. Sort the edges of G in ascending (non-decreasing) order;
4. For each edge (u, v) from the sored list of step 3.
      If u and v belong to different sets
         Add (u,v) to T;
         Get together u and v in one single set;
5. Return T
</pre>
<p>A great feature about the Kruskal&#8217;s algorithm is that it also work on disconnected graphs.</p>
<h2>History</h2>
<p>Kruskal’s algorithm is named after <a href="http://en.wikipedia.org/wiki/Joseph_Kruskal" title="Joseph Kruskal" target="_blank">Joseph Kruskal</a>, who wasn’t only computer scientist, but also prominent mathematician and statistician. Although he is best known for its algorithm for computing the minimum spanning tree, described in this post, he’s also known with his work as a statistician and his contribution to the formulation of multidimensional scaling. </p>
<p>Kruskal also explored the Indo-European languages contributing the studies of the linguistics along with other scientists. His “Indo-European Lexicographical List” (http://www.wordgumbo.com/ie/cmp/) is still widely used.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/11/19/computer-algorithms-prims-minimum-spanning-tree/" rel="bookmark" title="Computer Algorithms: Prim&#8217;s Minimum Spanning Tree">Computer Algorithms: Prim&#8217;s Minimum Spanning Tree </a></li>
<li><a href="/2012/11/05/computer-algorithms-minimum-spanning-tree/" rel="bookmark" title="Computer Algorithms: Minimum Spanning Tree">Computer Algorithms: Minimum Spanning Tree </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="/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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/11/12/computer-algorithms-kruskals-minimum-spanning-tree/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<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: Stack and Queue</title>
		<link>/2012/06/05/computer-algorithms-stack-and-queue-data-structure/</link>
		<comments>/2012/06/05/computer-algorithms-stack-and-queue-data-structure/#comments</comments>
		<pubDate>Tue, 05 Jun 2012 09:54:13 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[$_head]]></category>
		<category><![CDATA[Abstract data type]]></category>
		<category><![CDATA[computer algorithms]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Extinction]]></category>
		<category><![CDATA[FALSE]]></category>
		<category><![CDATA[heapsort algorithm]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[LIFO]]></category>
		<category><![CDATA[Linked list]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pointer]]></category>
		<category><![CDATA[Queue]]></category>
		<category><![CDATA[Shunting-yard algorithm]]></category>
		<category><![CDATA[Stack]]></category>
		<category><![CDATA[Subroutine]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Web browser]]></category>
		<category><![CDATA[web programming]]></category>

		<guid isPermaLink="false">/?p=3173</guid>
		<description><![CDATA[Introduction Every developer knows that computer algorithms are tightly related to data structures. Indeed many of the algorithms depend on a data structures and can be very effective for some data structures and ineffective for others. A typical example of this is the heapsort algorithm, which depends on a data structure called “heap”. In this &#8230; <a href="/2012/06/05/computer-algorithms-stack-and-queue-data-structure/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Stack and Queue</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/" rel="bookmark" title="Friday Algorithms: A Data Structure: JavaScript Stack">Friday Algorithms: A Data Structure: JavaScript Stack </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>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2017/09/14/data-structures-infographic-stack-queue/" rel="bookmark" title="Data Structures Infographic: Stack &#038; Queue">Data Structures Infographic: Stack &#038; Queue </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Every developer knows that <a href="/category/algorithms/" title="Algorithms on stoimen.com">computer algorithms</a> are tightly related to data structures. Indeed many of the algorithms depend on a data structures and can be very effective for some data structures and ineffective for others. A typical example of this is the heapsort algorithm, which depends on a data structure called “heap”. In this case although the stack and the queue are data structures instead of pure algorithms it&#8217;s imporant to understand their structure and the way they operate over data. </p>
<p>However, before we continue with the concrete realization of the stack and the queue, let’s first take a look on the definition of this term. A data structure is a logical abstraction that “models” the real world and presents (stores) our data in a specific format. The access to this data structure is often predefined thus we can access directly every item containing data. This help us to perform a different kind of tasks and operations over different kind of data structures &#8211; insert, delete, search, etc.. A typical data structures are the stack, the queue, the linked list and the tree.</p>
<p>All these structures help us perform specific operations effectively. For instance searching in a balanced tree is faster than searching in a linked list.</p>
<p>It is also very important to note that data structures can be represented in many different ways. We can model them using arrays or pointers, as shown in this post. In fact the most important thing is to represent the logical structure of the data structure you’re modeling. Thus the stack is a structure that follows the LIFO (Last In First Out) principle and it doesn’t matter how it is represented in our program (whether it will be coded with an array or with pointers). The important thing into a stack representation is to follow the LIFO principle correctly. In this case if the stack is an array only its top should be accessible and the only operation must be inserting new top of the stack.<br />
<span id="more-3173"></span></p>
<h2>Overview</h2>
<p>The stack and the queue are somehow related data structures as they represent two parts of somehow identical logics. Thus they are commonly described in pair.</p>
<h3>Stack</h3>
<p>The stack data structure models the real-world stack. You can think of it as stack of boxes one above the other. Thus the only way to put another item into the stack is to put it above all other items (on its top). This operation is often called “push”. In the other hand taking an item from the stack is called pop, and also only the highest item can be “poped”. The following image describes better the structure of the stack and its operations &#8211; push and pop.</p>
<figure id="attachment_3178" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/1.-Stack-Operations.png"><img src="/wp-content/uploads/2012/06/1.-Stack-Operations.png" alt="Stack Operations" title="Stack Operations" width="620" height="444" class="size-full wp-image-3178" srcset="/wp-content/uploads/2012/06/1.-Stack-Operations.png 620w, /wp-content/uploads/2012/06/1.-Stack-Operations-300x214.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The operations of insert and delete an item from the stack are commonly called push and pop!</figcaption></figure>
<p>We see here how computer data structures model the real world. The stack data structure indeed makes no exception and models the real-world stacks.</p>
<h3>Stack Implementation</h3>
<p>As I said a stack can be implemented in some different ways. The first approach is to use an array (using the specific language syntax of the programming language of your choice). Here’s the implementation of a stack using an array in <a href="/category/php/" title="PHP on stoimen.com">PHP</a>.</p>
<pre lang="PHP">
$stack = array();

function push($data, &$stack) {
	$stack[] = $data;
}

function pop(&$stack)
{
	$len = count($stack);
	$top = $stack[$len-1];
	
	unset($stack[$len-1]);
	
	return $top;
}

// array()
print_r($stack);

push(1, $stack);
push(2, $stack);
push('some test', $stack);
push(array(25,12,1999), $stack);

// [1, 2, 'some test', [25, 12, 1999]]
print_r($stack);

// [25, 12, 1999]
echo pop($stack);
// 'some test'
echo pop($stack);

// [1, 2]
print_r($stack);
</pre>
<p>However there are much easier ways to do the same thing with PHP since there are lots of predefined functions that work with stacks.</p>
<pre lang="PHP">
$stack = array();

function push($data, &$stack) {
	$stack[] = $data;
}

function pop(&$stack)
{
	return array_pop($stack);
}

// array()
print_r($stack);

push(1, $stack);
push(2, $stack);
push('some test', $stack);
push(array(25,12,1999), $stack);

// [1, 2, 'some test', [25, 12, 1999]]
print_r($stack);

// [25, 12, 1999]
echo pop($stack);
// 'some test'
echo pop($stack);

// [1, 2]
print_r($ret);
</pre>
<p>As in many programming languages here the example makes use of integers but it can be modified to work with more complex data types as objects, mutli dimensional arrays, etc. However we can use a higher level abstraction in order to represent a stack. Here&#8217;s a short example of a stack using pointers. The stack class only holds a pointer to the top of the stack. Thus only the top can be &#8220;poped&#8221;. Also each elements points to its predecessor. Using this abstraction we&#8217;re sure that the programmer can perform only these two operations &#8211; &#8220;pop&#8221; and &#8220;push&#8221;.</p>
<pre lang="PHP">
class Struct
{
	protected $_data = null;
	protected $_next = null;
	
	public function __construct($data, $next)
	{
		$this->_data = $data;
		$this->_next = $next;
	}
	
	public function getData()
	{
		return $this->_data;
	}
	
	public function setData(&$data)
	{
		$this->_data = $data;
	}
	
	public function getNext()
	{
		return $this->_next;
	}
	
	public function setNext(&$next)
	{
		$this->_next = $next;
	}
}

class Stack
{
	protected $_top = null;
	
	public function push($data)
	{
		$item = new Struct($data, null);
		
		if ($this->_top == null) {
			$this->_top = $item;
		} else {
			$item->setNext($this->_top);
			$this->_top = $item;
		}
	}

	public function pop()
	{
		if ($this->_top) {
			$t = $this->_top;
			$data = $t->getData();
			
			$this->_top = $this->_top->getNext();
			
			$t = null;
			
			return $data;
		}
	}
	
	public function __toString()
	{
		$output = '';
		$t = $this->_top;
		while ($t) {
			$output .= $t->getData() . ' ';
			$t = $t->getNext();
		}
		
		return $output;
	}
}

$s = new Stack();
$s->push(1);
$s->push(2);
$s->push(3);

// 3 2 1
echo $s;

$s->pop();
$s->pop();

// 1
echo $s;
</pre>
<h3>Queue</h3>
<p>As mentioned above the queue is somehow related to the stack data structure. However it follows a different principle &#8211; FIFO (First In First Out), which means that the item that has been in the queue for the longest time is retrieved first.</p>
<figure id="attachment_3177" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/2.-Queue-Operations.png"><img src="/wp-content/uploads/2012/06/2.-Queue-Operations.png" alt="Queue Operations" title="Queue Operations" width="618" height="232" class="size-full wp-image-3177" srcset="/wp-content/uploads/2012/06/2.-Queue-Operations.png 618w, /wp-content/uploads/2012/06/2.-Queue-Operations-300x112.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Inserting and deleting from a queue happen in the opposite sites of the queue!</figcaption></figure>
<p>This comes again from the real world, where we can think of a queue of people waiting in front of a movie theater. In this case the person that has waited the most takes its ticket first.</p>
<h3>Queue Implementation</h3>
<p>An array representation of a queue isn’t a difficult task. However the only example of a queue here is using pointers. Indeed the following code syntax is very tightly related to PHP so only the main principles of supporting a queue functionality is important.</p>
<pre lang="PHP">
class Item
{
	public $data = null;
	public $next = null;
	public $prev = null;
	
	public function __construct($data)
	{
		$this->data = $data;
	}
}

class Queue
{
	protected $_head = null;
	protected $_tail = null;
	
	public function insert($data)
	{
		$item = new Item($data);
		
		if ($this->_head == NULL) {
			$this->_head = $item;
		} else if ($this->_tail == NULL) {
			$this->_tail = $item;
			$this->_head->next = $this->_tail;
			$this->_tail->prev = $this->_head;
		} else {
			$this->_tail->next = $item;
			$item->prev = $this->_tail;
			$this->_tail = $item;
		}
	}
	
	public function delete()
	{
		if (isset($this->_head->data)) {
			
			$temp = $this->_tail;
			$data = $temp->data;
			
			$this->_tail = $this->_tail->prev;
			
			if (isset($this->_tail->next))
				$this->_tail->next = null;
			else 
				$this->_tail = $this->_head = null;
			
			return $data;
		}
		
		return FALSE;
	}
	
	public function __toString()
	{
		$output = '';
		$t = $this->_head;
		while ($t) {
			$output .= $t->data . ' | ';
			$t = $t->next;
		}
		
		return $output;
	}
}


$q = new Queue();

$q->insert(1);
$q->insert(2);
$q->insert(3);

// 1 2 3
echo $q;

$q->delete();
$q->delete();

// 1
echo $q;

$q->insert(15);
$q->insert('hello');
$q->insert('world');
$q->delete();

// 1 15 "hello"
echo $q;
</pre>
<h2>Application</h2>
<p>Stacks and queues are widely used in programming. By defining stacks and queues we somehow predefine the way our data structure is accessed, thus we&#8217;re sure that our program will access the data in a specific manner. For instance if we code a queue for a list or upcomming commands, we&#8217;re sure that the most waited command will be executed first. In this case we predefine the order the commands are processed. In the web programming, especially in JavaScript, every developer knows what&#8217;s an event fired in a web browser environemtn. In case of many events, they&#8217;re putted into a queue and they are executed consecutively in the order they were fired by the user.</p>
<p>Another example is the execution stack of most of the programming compilers and interpreters. We know that in a OOP languages, such as PHP for instance, there&#8217;s a stack of function calls. In case of failure we can easily see the &#8220;stack trace&#8221;.</p>
<p>You see how many examples of queues and stacks there are in the real-world programming. These two structures are easy to implement yet very important in order to understand other more complex data structures as linked lists and trees.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/" rel="bookmark" title="Friday Algorithms: A Data Structure: JavaScript Stack">Friday Algorithms: A Data Structure: JavaScript Stack </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>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2017/09/14/data-structures-infographic-stack-queue/" rel="bookmark" title="Data Structures Infographic: Stack &#038; Queue">Data Structures Infographic: Stack &#038; Queue </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/06/05/computer-algorithms-stack-and-queue-data-structure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Lossy Image Compression with Run-Length Encoding</title>
		<link>/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/</link>
		<comments>/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/#comments</comments>
		<pubDate>Thu, 03 May 2012 20:27:06 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Coding theory]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[data compression algorithm]]></category>
		<category><![CDATA[Graphics file formats]]></category>
		<category><![CDATA[image compression]]></category>
		<category><![CDATA[Image processing]]></category>
		<category><![CDATA[Information theory]]></category>
		<category><![CDATA[jpeg]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[lossy algorithm]]></category>
		<category><![CDATA[Lossy compression]]></category>
		<category><![CDATA[PCX]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pixel]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[suitable algorithm]]></category>
		<category><![CDATA[Technology/Internet]]></category>

		<guid isPermaLink="false">/?p=3078</guid>
		<description><![CDATA[Introduction Run-length encoding is a data compression algorithm that helps us encode large runs of repeating items by only sending one item from the run and a counter showing how many times this item is repeated. Unfortunately this technique is useless when trying to compress natural language texts, because they don’t have long runs of &#8230; <a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Lossy Image 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/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length 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>
<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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" title="Computer Algorithms: Data Compression with Run-length Encoding">Run-length encoding</a> is a data compression algorithm that helps us encode large runs of repeating items by only sending one item from the run and a counter showing how many times this item is repeated. Unfortunately this technique is useless when trying to compress natural language texts, because they don’t have long runs of repeating elements. In the other hand RLE is useful when it comes to image compression, because images happen to have long runs pixels with identical color. </p>
<p>As you can see on the following picture we can compress consecutive pixels by only replacing each run with one pixel from it and a counter showing how many items it contains.</p>
<figure id="attachment_3101" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/1.LosslessRLEforImages.png"><img src="/wp-content/uploads/2012/05/1.LosslessRLEforImages.png" alt="Lossless RLE for Images" title="Lossless RLE for Images" width="619" height="216" class="size-full wp-image-3101" srcset="/wp-content/uploads/2012/05/1.LosslessRLEforImages.png 619w, /wp-content/uploads/2012/05/1.LosslessRLEforImages-300x104.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">Although lossless RLE can be quite effective for image compression, it is still not the best approach!</figcaption></figure>
<p>In this case we can save only counters for pixels that are repeated more than once. Such the input stream “aaaabbaba” will be compressed as “[4]a[2]baba”. </p>
<p>Actually there are several ways run-length encoding can be used for image compression. A possible way of compressing a picture can be either row by row or column by column, as it is shown on the picture below.</p>
<p><figure id="attachment_3102" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/2.RowbyRowandColbyCol.png"><img src="/wp-content/uploads/2012/05/2.RowbyRowandColbyCol.png" alt="Row by row or column by column compression" title="Row by row or column by column compression" width="621" height="300" class="size-full wp-image-3102" srcset="/wp-content/uploads/2012/05/2.RowbyRowandColbyCol.png 621w, /wp-content/uploads/2012/05/2.RowbyRowandColbyCol-300x144.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Row by row or column by column compression.</figcaption></figure><span id="more-3078"></span></p>
<p>The problem in practice is that sometimes compressing row by row may be effective, while in other cases the same approach is very ineffective. This is illustrated by the image below.</p>
<figure id="attachment_3103" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression.png"><img src="/wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression.png" alt="Effective and Ineffective Compression" title="Effective and Ineffective Compression" width="621" height="328" class="size-full wp-image-3103" srcset="/wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression.png 621w, /wp-content/uploads/2012/05/3.EffectiveandIneffectiveCompression-300x158.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Sometimes image compression may be done only after some preprocessing that can help us understand the best compression approach!</figcaption></figure>
<p>Obviously run-length encoding is a very good approach when compressing images, however when we talk about big images with millions of pixels it’s somehow natural to come with some lossy compression.</p>
<h2>Overview</h2>
<p>Lossy RLE is a very suitable algorithm when it comes to images, because in most of the cases large images do appear to have big spaces of identical pixel colors, i.e. when the half of the picture is the blue sky. By using lossy compression we can skip very short runs.</p>
<p>First we’ve to say how long will be the shortest run that we will keep in the compression. For instance if 3 is the shortest run, then runs of 2 consecutive elements will be skipped.</p>
<figure id="attachment_3104" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/4.LossessImageRow.png"><img src="/wp-content/uploads/2012/05/4.LossessImageRow.png" alt="Lossless Pixel Row" title="Lossless Pixel Row" width="621" height="173" class="size-full wp-image-3104" srcset="/wp-content/uploads/2012/05/4.LossessImageRow.png 621w, /wp-content/uploads/2012/05/4.LossessImageRow-300x83.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Lossless compression of a pixel row in some cases can be very inefective!</figcaption></figure>
<p>Of course if we set the shortest run to be only one element long, this will make our compression completely lossless, which isn’t very effective. However when we talk about millions of pixels even runs of three or more elements are very short, so it’s up to the developer to decide how long will be the shortest run.</p>
<h3>Some Examples</h3>
<p>Let&#8217;s first define the shortest run that we will keep untouched to be at least three element long.</p>
<figure id="attachment_3105" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/5.LossyImageRow.png"><img src="/wp-content/uploads/2012/05/5.LossyImageRow.png" alt="Lossy Pixel Row" title="Lossy Pixel Row" width="620" height="273" class="size-full wp-image-3105" srcset="/wp-content/uploads/2012/05/5.LossyImageRow.png 620w, /wp-content/uploads/2012/05/5.LossyImageRow-300x132.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We can lose some information that is invisbile to the eye.</figcaption></figure>
<p>The above image is compressed more effectively than the lossless pixel row from the previous picture.</p>
<p>The thing is how to merge short runs. For instance the following three runs have to be blended into one color run.</p>
<figure id="attachment_3106" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/6.BlendingShortRuns.png"><img src="/wp-content/uploads/2012/05/6.BlendingShortRuns.png" alt="Blending Short Runs" title="Blending Short Runs" width="620" height="199" class="size-full wp-image-3106" srcset="/wp-content/uploads/2012/05/6.BlendingShortRuns.png 620w, /wp-content/uploads/2012/05/6.BlendingShortRuns-300x96.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We must chose how to blend short runs!</figcaption></figure>
<p>We can choose the middle color (option #1) or not, but this will always depend on the picture and it will be effective in some cases and ineffective in other.</p>
<h2>Implementation</h2>
<p>Implementing run-length encoding is easy in general. Here’s a simple <a href="/category/php/" title="PHP on stoimen.com">PHP</a> code that shows a lossy RLE.</p>
<pre lang="PHP">
/**
 * Compresses an input list of objects by losing some data using
 * run-length encoding
 * 
 * @param mixed $objectList
 * @param int $minLength
 */
function lossyRLE($objectList, $minLength)
{
	$len 		= is_string($objectList) 
			? strlen($objectList)		// string as an input stream
			: count($objectList);		// array as an input stream
	$j 		= 1;
	$compressed = array();				// compressed output
	
	for ($i = 0; $i < $len; $i++) {
		if (isset($objectList[$i+1]) &#038;&#038; $objectList[$i] == $objectList[$i+1]) {
			$j++;
		} else {
			$l = count($compressed);
			// This is where RLE is converted to a lossy algorithm!
			// In case the run is shorter than a predefined length the
			// algorithm will skip these elements and will stretch the last
			// saved run.
			// NOTE: this logic can be changed in order to take other
			// decisions depending on the goals.
			if ($j < $minLength &#038;&#038; $j < $l) {
				$compressed[$l-1]['count'] += $j;
			} else {
				$compressed[] = array('count' => $j, $objectList[$i]);
			}
			$j = 1;
		}
	}
	
	return $compressed;
}

$input = 'aaaabbaabbbbba';

// aaaaaaaabbbbbb
lossyRLE($input, 3);
</pre>
<p>The code above can be modified in order to work with more complex data. Let’s say we have a “pixel” abstraction as on the example above.</p>
<pre lang="PHP">
/**
 * Pixel abstraction
 */
class Pixel
{
	private $_color = null;
	
	public function __construct($color = '')
	{
		$this->_color = $color;
	}
	
	public function getColor() 
	{
		return $this->_color;
	}
}

/**
 * Inits the pixels array
 * 
 * @param array $pixels
 */
function init(array &$pixels = array())
{
	$colors = array('red', 'green', 'blue');
	
	for ($i = 0; $i < 100; $i++) {
		$pixels[] = new Pixel($colors[mt_rand(0, 2)]);
	}
}

/**
 * Compresses an input list of objects by losing some data using
 * run-length encoding
 * 
 * @param mixed $objectList
 * @param int $minLength
 */
function lossyRLE($objectList, $minLength)
{
	$len 		= is_string($objectList) 
			? strlen($objectList)		// string as an input stream
			: count($objectList);		// array as an input stream
	$j 		= 1;
	$compressed = array();				// compressed output
	
	for ($i = 0; $i < $len; $i++) {
		if (isset($objectList[$i+1]) &#038;&#038; $objectList[$i] == $objectList[$i+1]) {
			$j++;
		} else {
			$l = count($compressed);
			// This is where RLE is converted to a lossy algorithm!
			// In case the run is shorter than a predefined length the
			// algorithm will skip these elements and will stretch the last
			// saved run.
			// NOTE: this logic can be changed in order to take other
			// decisions depending on the goals.
			if ($j < $minLength &#038;&#038; $l > $j) {
				$compressed[$l-1]['count'] += $j;
			} else {
				$compressed[] = array('count' => $j, $objectList[$i]);
			}
			$j = 1;
		}
	}
	
	return $compressed;
}

$pixels = array();

// initializes the pixels array
init($pixels);

$compressed = lossyRLE($pixels, 3);

print_r($compressed);
</pre>
<h2>Complexity</h2>
<p>In general lossless RLE compelxity is linear &#8211; O(n) where n is the number of items from the input stream. Even with the small modification above the complexity remains linear. However we can modify the compression in a slightly different manner (in order to get the middle value from consecutive short runs). This will somehow affect the complexity of the algorithm, of course.</p>
<h2>Application</h2>
<p>Run-length encoding isn’t a very effective option when compressing texts, but for images where long runs of the identical pixels happen to occur it is quite useful. </p>
<figure id="attachment_3107" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/7.LossyRLE.png"><img src="/wp-content/uploads/2012/05/7.LossyRLE.png" alt="Lossy RLE in Practice" title="Lossy RLE in Practice" width="622" height="483" class="size-full wp-image-3107" srcset="/wp-content/uploads/2012/05/7.LossyRLE.png 622w, /wp-content/uploads/2012/05/7.LossyRLE-300x232.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>Nevertheless RLE is easy to convert into a lossy algorithm, that makes it very suitable for image compression.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length 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>
<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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Brute Force String Matching</title>
		<link>/2012/03/27/computer-algorithms-brute-force-string-matching/</link>
		<comments>/2012/03/27/computer-algorithms-brute-force-string-matching/#comments</comments>
		<pubDate>Tue, 27 Mar 2012 07:21:41 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Bitap algorithm]]></category>
		<category><![CDATA[Boyer–Moore string search algorithm]]></category>
		<category><![CDATA[brute force algorithms]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[pre-processing]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[String algorithms]]></category>
		<category><![CDATA[string matching algorithm]]></category>
		<category><![CDATA[String searching algorithm]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[text processing software]]></category>

		<guid isPermaLink="false">/?p=2966</guid>
		<description><![CDATA[Introduction String matching is something crucial for database development and text processing software. Fortunately every modern programming language and library is full of functions for string processing that help us in our everyday work. However is great to understand their principles. String algorithms can be mainly divided into several categories. One of these categories is &#8230; <a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Brute Force String Matching</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" rel="bookmark" title="Computer Algorithms: Morris-Pratt String Searching">Computer Algorithms: Morris-Pratt String Searching </a></li>
<li><a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" rel="bookmark" title="Computer Algorithms: Boyer-Moore String Searching">Computer Algorithms: Boyer-Moore String Searching </a></li>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>String matching is something crucial for database development and text processing software. Fortunately every modern programming language and library is full of functions for string processing that help us in our everyday work. However is great to understand their principles.</p>
<p>String algorithms can be mainly divided into several categories. One of these categories is string matching.</p>
<p>When we come to string matching the most basic approach is what is known as brute force, which means just to check every single character from the text to match against the pattern. In general we have a text and a pattern (most commonly shorter than the text). What we need to do is to answer the question whether this pattern appears into the text.</p>
<h2>Overview</h2>
<p>The principles of brute force string matching are quite simple. We must check for a match between the first characters of the pattern with the first character of the text as on the picture bellow.</p>
<p><figure id="attachment_2977" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/FirstStepBruteforcestringmatching.png"><img src="/wp-content/uploads/2012/03/FirstStepBruteforcestringmatching.png" alt="First step of brute force string matching" title="First step of brute force string matching" width="618" height="236" class="size-full wp-image-2977" srcset="/wp-content/uploads/2012/03/FirstStepBruteforcestringmatching.png 618w, /wp-content/uploads/2012/03/FirstStepBruteforcestringmatching-300x114.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">We start by comparing the first characters of the text and the pattern!</figcaption></figure> <span id="more-2966"></span><br />
If they don’t match we move forward the second character of the text. Now we compare the first character of the pattern with the second character of the text. If they don’t match again we move forward until we get a match or until we reach the end of the text. </p>
<figure id="attachment_2982" style="width: 612px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/SecondStepBruteforcestringmatching.png"><img src="/wp-content/uploads/2012/03/SecondStepBruteforcestringmatching.png" alt="Second step of brute force string matching" title="Second step of brute force string matching" width="612" height="241" class="size-full wp-image-2982" srcset="/wp-content/uploads/2012/03/SecondStepBruteforcestringmatching.png 612w, /wp-content/uploads/2012/03/SecondStepBruteforcestringmatching-300x118.png 300w" sizes="(max-width: 612px) 100vw, 612px" /></a><figcaption class="wp-caption-text">Because the first character of the text and the pattern don&#039;t match, we move forward the second character of the text. Now we compare the second character of the text with the first character of the pattern!</figcaption></figure>
<p>In case they match we move forward the second character of the pattern comparing it with the “next” character of the text, as on the picture bellow.</p>
<figure id="attachment_2981" style="width: 617px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/ThirdStepBruteforcestringmatching.png"><img src="/wp-content/uploads/2012/03/ThirdStepBruteforcestringmatching.png" alt="Third step of  brute force string matching" title="Third step of  brute force string matching" width="617" height="235" class="size-full wp-image-2981" srcset="/wp-content/uploads/2012/03/ThirdStepBruteforcestringmatching.png 617w, /wp-content/uploads/2012/03/ThirdStepBruteforcestringmatching-300x114.png 300w" sizes="(max-width: 617px) 100vw, 617px" /></a><figcaption class="wp-caption-text">If case a character from the text match against the first character of the pattern we move forward to the second character of the pattern and the next character of the text!</figcaption></figure>
<p>Just because we have found a match between the first character from the pattern with some character of the text, doesn’t mean that the pattern appears in the text. We must move forward to see whether the full pattern is contained into the text. </p>
<figure id="attachment_2980" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/MatchBruteforcestringmatching.png"><img src="/wp-content/uploads/2012/03/MatchBruteforcestringmatching.png" alt="Match in brute force string matching" title="Match in brute force string matching" width="619" height="229" class="size-full wp-image-2980" srcset="/wp-content/uploads/2012/03/MatchBruteforcestringmatching.png 619w, /wp-content/uploads/2012/03/MatchBruteforcestringmatching-300x110.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">The pattern is matched!</figcaption></figure>
<h2>Implementation</h2>
<p>Implementation of brute force string matching is easy and here we can see a short PHP example. The bad news is that naturally this algorithm is quite slow.</p>
<pre lang="PHP">
function sub_string($pattern, $subject) 
{
	$n = strlen($subject);
	$m = strlen($pattern);
	
	for ($i = 0; i < $n-$m; $i++) {
		$j = 0;
		while ($j < $m &#038;&#038; $subject[$i+$j] == $pattern[$j]) {
			$j++;
		}
		if ($j == $m) return $i;
	}
	return -1;
}

echo sub_string('o wo', 'hello world!');

</pre>
<h2>Complexity</h2>
<p>As I said this algorithm is slow. Actually every algorithm that contains “brute force” in its name is slow, but to show how slow is string matching I can say that its complexity is O(n.m). Here <strong>n</strong> is the length of the text, while <strong>m</strong> is the length of the pattern.</p>
<figure id="attachment_2978" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart1.png"><img src="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart1.png" alt="Brute force string matching complexity chart 1" title="Brute force string matching complexity chart 1" width="600" height="371" class="size-full wp-image-2978" srcset="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart1.png 600w, /wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart1-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">For fixed pattern length of m = 5, we can see that even for relatively short text the time grows quickly!</figcaption></figure>
<p>In case we fix the length of the text and test against variable length of the pattern, again we get rapidly growing function.</p>
<figure id="attachment_2979" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart2.png"><img src="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart2.png" alt="Brute force string matching complexity chart 2" title="Brute force string matching complexity chart 2" width="600" height="371" class="size-full wp-image-2979" srcset="/wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart2.png 600w, /wp-content/uploads/2012/03/BruteForceStringMatchingComplexityChart2-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h2>Application</h2>
<p>Brute force string matching can be very ineffective, but it can also be very handy in some cases. Just like the <a href="/2011/11/24/computer-algorithms-sequential-search/" title="Computer Algorithms: Sequential Search">sequential search</a>.</p>
<h3>It can be very useful ...</h3>
<ol>
<li>Doesn't require pre-processing of the text - Indeed if we search the text only once we don't need to pre-process it. Most of the algorithms for string matching need to build an index of the text in order to search quickly. This is great when you've to search more than once into a text, but if you do only once, perhaps (for short texts) brute force matching is great!</li>
<li>Doesn't require additional space - Because brute force matching doesn't need pre-processing it also doesn't require more space, which is one cool feature of this algorithm</li>
<li>Can be quite effective for short texts and patterns</li>
</ol>
<h3>It can be ineffective ...</h3>
<ol>
<li>If we search more than once the text - As I said in the previous section if you perform the search more than once it's perhaps better to use another string matching algorithm that builds an index and it's faster.</li>
<li>It's slow - In general brute force algorithms are slow and brute force matching isn't an exception.</li>
</ol>
<h2>Final Words</h2>
<p>String matching is something very special in software development and it is used in various cases, so every developer must be familiar with this topic.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" rel="bookmark" title="Computer Algorithms: Morris-Pratt String Searching">Computer Algorithms: Morris-Pratt String Searching </a></li>
<li><a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" rel="bookmark" title="Computer Algorithms: Boyer-Moore String Searching">Computer Algorithms: Boyer-Moore String Searching </a></li>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/03/27/computer-algorithms-brute-force-string-matching/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>5 Tips on How to Spot a Bad Developer and Team Member</title>
		<link>/2012/03/02/5-tips-on-how-to-spot-a-bad-developer-and-team-member/</link>
		<comments>/2012/03/02/5-tips-on-how-to-spot-a-bad-developer-and-team-member/#comments</comments>
		<pubDate>Fri, 02 Mar 2012 11:41:22 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[web development]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[programmer]]></category>
		<category><![CDATA[team member]]></category>
		<category><![CDATA[Technology/Internet]]></category>

		<guid isPermaLink="false">/?p=2811</guid>
		<description><![CDATA[1. He hates libraries, framworks and cutting edge technologies He always hates newest technologies and considers that pure programming with no libraries and frameworks is the masterpiece of coding and only way to show his greatness. Any mention of a library name results in something like &#8220;blah, this sucks&#8221; with no explanation why. However most &#8230; <a href="/2012/03/02/5-tips-on-how-to-spot-a-bad-developer-and-team-member/" class="more-link">Continue reading <span class="screen-reader-text">5 Tips on How to Spot a Bad Developer and Team Member</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/06/12/joomla-old-code-or-bad-code/" rel="bookmark" title="Joomla! &#8211; Old Code or Bad Code?">Joomla! &#8211; Old Code or Bad Code? </a></li>
<li><a href="/2010/02/19/jquery-tips-storing-data/" rel="bookmark" title="jQuery tips &#8211; storing data">jQuery tips &#8211; storing data </a></li>
<li><a href="/2009/05/25/ie-developer-tools/" rel="bookmark" title="IE developer tools">IE developer tools </a></li>
<li><a href="/2010/10/04/some-php-tips-basename/" rel="bookmark" title="Some PHP Tips: basename()">Some PHP Tips: basename() </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>1. He hates libraries, framworks and cutting edge technologies</h2>
<p>He always hates newest technologies and considers that pure programming with no libraries and frameworks is the masterpiece of coding and only way to show his greatness. Any mention of a library name results in something like &#8220;blah, this sucks&#8221; with no explanation why. However most often the reason is &#8220;because it’s slow&#8221; with no examples of how slow actually this library is &#8211; he does not make any performance tests at all. Always prefers to write his own pure “javascript” or “php” based code/library because he thinks this is the cutting edge of modern technology. </p>
<h2>2. He hates helping and talking to clients</h2>
<p>Always after a phone call with a client he’s angry, because “the sutpid client” doesn’t understand his way of brilliant thinking. He thinks that a project must exists just to show what a “good” developer he is and how much he knows, not because the product will be someday, somehow used by poor clients.</p>
<h2>3. He loves to see how others make mistakes</h2>
<p>Bugs by other developers are always accepted with a smile with some words like “I told you”. He doesn’t think bugs will be comited if he were the developer. However bugs in his code are always accepted and explained as misconseption of the client!</p>
<h2>4. Always negative at meetings</h2>
<p>Whatever solution is proposed on a meeting he’s negative. But he doesn’t propose his own solution. Typically a bad team member is always trying to say &#8220;whatever solution you get I’m telling you that there are some pitfalls&#8221;.</p>
<h2>5. He hates interviews</h2>
<p>Because he thinks he’s the best programmer in the world, he hates going to interviews. His behaviour on interviews is always like “you know less than me and I don’t know why I’m here”. However once he gets the job he behaves with his boss like “I’m making you a favor to receive a salary from you!”</p>
<p>Advice: To avoid working with such jerks try to spot them on the interview. If he tells you that your choice of library and technology sucks you should better get another candidate.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/06/12/joomla-old-code-or-bad-code/" rel="bookmark" title="Joomla! &#8211; Old Code or Bad Code?">Joomla! &#8211; Old Code or Bad Code? </a></li>
<li><a href="/2010/02/19/jquery-tips-storing-data/" rel="bookmark" title="jQuery tips &#8211; storing data">jQuery tips &#8211; storing data </a></li>
<li><a href="/2009/05/25/ie-developer-tools/" rel="bookmark" title="IE developer tools">IE developer tools </a></li>
<li><a href="/2010/10/04/some-php-tips-basename/" rel="bookmark" title="Some PHP Tips: basename()">Some PHP Tips: basename() </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/03/02/5-tips-on-how-to-spot-a-bad-developer-and-team-member/feed/</wfw:commentRss>
		<slash:comments>6</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 Prefix Encoding</title>
		<link>/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/</link>
		<comments>/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/#respond</comments>
		<pubDate>Mon, 06 Feb 2012 20:50:58 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Apple Inc.]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[Decoder]]></category>
		<category><![CDATA[Delta encoding]]></category>
		<category><![CDATA[Dictionary coder]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[Johnson Clarkson Jackson]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[mobile device]]></category>
		<category><![CDATA[same algorithm]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Trie]]></category>
		<category><![CDATA[United Kingdom]]></category>
		<category><![CDATA[Yahoo! Inc.]]></category>

		<guid isPermaLink="false">/?p=2699</guid>
		<description><![CDATA[Overview Prefix encoding, sometimes called front encoding, is yet another algorithm that tries to remove duplicated data in order to reduce its size. Its principles are simple, however this algorithm tend to be difficult to implement. To understand why, first let’s take a look of its nature. Please, have a look on the following dictionary. &#8230; <a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Prefix Encoding</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </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>
<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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>Prefix encoding, sometimes called front encoding, is yet another algorithm that tries to remove duplicated data in order to reduce its size. Its principles are simple, however this algorithm tend to be difficult to implement. To understand why, first let’s take a look of its nature.</p>
<p>Please, have a look on the following dictionary.</p>
<pre lang="PHP">
use
used
useful
usefully
usefulness
useless
uselessly
uselessness
</pre>
<p>Instead of keeping all these words in plain text or transferring all them over a network, we can compress (encode) them with prefix encoding. </p>
<p><figure id="attachment_2700" style="width: 299px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/Prefixencoding.png"><img src="/wp-content/uploads/2012/02/Prefixencoding.png" alt="Prefix Encoding" title="Prefix encoding" width="299" height="457" class="size-full wp-image-2700" srcset="/wp-content/uploads/2012/02/Prefixencoding.png 299w, /wp-content/uploads/2012/02/Prefixencoding-196x300.png 196w" sizes="(max-width: 299px) 100vw, 299px" /></a><figcaption class="wp-caption-text"> </figcaption></figure><br />
<span id="more-2699"></span><br />
It’s clear that each of these words begin with the prefix “use” which is also the first word from the list. So we can easily compress them into the following array.</p>
<pre lang="PHP">
$data = array(
0 => 'use',
1 => '0d',
2 => '0ful',
3 => '0fully',
4 => '0less',
5 => '0lessly',
6 => '0lessness',
);
</pre>
<p>It’s clear that this is not the best compression and we can go even further by using not only the first word as prefix.</p>
<pre lang="PHP">
$data = array(
0 => 'use',
1 => '0d',
2 => '0ful',
3 => '2ly',
4 => '0less',
5 => '4ly',
6 => '4ness',
);
</pre>
<p>Now the compression is better and the good news is that decompression is a fairly simple process. However the tricky part is compression itself. The problem is that it is quite difficult to chose an appropriate prefix. In our first example this is simple, but most of the times in practice we can have more heterogeneous data. Indeed the process of compression can be very difficult for randomly generated data and the algorithm will be not only slow, but difficult to implement.</p>
<p>The good thing is that this algorithm can be used in many cases once we know the data format in advance. So let’s see three examples where this algorithm can be very handy.</p>
<h2>Application</h2>
<p>Here are three examples of prefix encoding. As I said above the process of compression can be very difficult for random data, so it is a good practice to use only it if you know in advance the format of the input data.</p>
<h3>Date and time prefixes</h3>
<p>We humans often skip the first two digits of an year, so for instance we don’t always write 1995 or 1996, but we use the shorter &#8211; ‘95 and ‘96. Thus years can be encoded with shorter strings.</p>
<pre lang="PHP">
input: 	(1991, 1992, 1993, 1994, 1995, 1996)
output:	(91, 92, 93, 94, 95, 96)
</pre>
<p>The problem is that with small changes of the input stream we can confuse the decoder. Thus if we add years from the 21st century we lose the uniqueness of the data.</p>
<pre lang="PHP">
input:	(1998, 1992, 1999, 2011, 2012)
output: (98, 92, 99, 11, 12)
</pre>
<p>Now the decoder can decode the last two values as (1911, 1912) as “19” is considered to be the prefix. So we must know in advance that our prefix is absolutely equal for each of the values. If not the encoding format must be different. For instance we can encode also the prefix, with some special maker.</p>
<pre lang="PHP">
input:	(1998, 1992, 1932, 1924, 2001, 2012)
output:	(#19, 98, 92, 32, 24, #20, 01, 12)
</pre>
<p>Once the decoder reads the # character it will know to decode the following number as prefix.</p>
<p>This can be used in practice for date and time formats. Let’s say we have some datetime values, but we know that all of them are in the same day.</p>
<pre lang="PHP">
2012-01-31 15:33:45
2012-01-31 16:12:11
2012-01-31 17:32:35
2012-01-31 18:54:34
</pre>
<p>Obviously we can omit the date part of these strings and send (keep) only the time. Once again, we must be absolutely sure that all these values are in the same day. If not, we can use the encoding strategy of the previous example.</p>
<h3>Phone numbers</h3>
<p>Phone numbers are the typical case of prefix encoding. Not only the international code, but also the mobile network operators use prefixes for their phone numbers. Thus if we have to transfer phone numbers from, let’s say the <strong>UK</strong>, we can replace the leading <strong>“+44”</strong> with something shorter. </p>
<p>If you happen to code a phone book for a mobile device you can spend some space by compressing the data using prefix encoding and thus the user will have more space and will store more phone numbers on his mobile.</p>
<p>Phone number prefixes can be also used for database normalization. Thus you can store them in a separate db table and leave only the unique numbers from the phonebook.</p>
<h3>Geo Coordinates</h3>
<p>Using the same example from <a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" title="Computer Algorithms: Data Compression with Relative Encoding">my previous post</a> we can send GEO coordinates by removing a common prefix, for large levels of zoom. Indeed when you’ve to send lots of markers to your map application you can expect all of these markers to be fairly close to each other in large zoom level.</p>
<figure id="attachment_2701" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/NY-map.png"><img src="/wp-content/uploads/2012/02/NY-map.png" alt="NY Subway Map" title="NY Subway Map" width="620" class="size-full wp-image-2701" srcset="/wp-content/uploads/2012/02/NY-map.png 843w, /wp-content/uploads/2012/02/NY-map-300x199.png 300w" sizes="(max-width: 843px) 100vw, 843px" /></a><figcaption class="wp-caption-text">On large zoom levels we can expect markers to be with the same prefix.</figcaption></figure>
<p>Now the coordinates of those points can have a common prefix, like the example bellow with the Subway stations.</p>
<pre lang="PHP">
LatLon(40.762959,-73.985989)
LatLon(40.761886,-73.983629)
LatLon(40.762861,-73.981612)
LatLon(40.764616,-73.98056)
</pre>
<p>We can see that all of these GEO points have the same prefix (40.76x, -73.98x), so we can send the prefix only once.</p>
<pre lang="PHP">
Prefix: (40.76, -73.98)
Data: 
LatLon(2959,5989)
LatLon(1886,3629)
LatLon(2861,1612)
LatLon(4616,056)
</pre>
<p>These are only three examples of prefix encoding and this algorithm must be considered as very useful when transferring homogeneous data. </p>
<h2>Suffix Encoding</h2>
<p>Suffix encoding practically the same algorithm as prefix encoding, with the small difference that we use to encode duplicating suffixes. Like the examples bellow suffix encoding can be useful is replacing repeating last name suffixes.</p>
<pre lang="PHP">
Johnson
Clarkson
Jackson
</pre>
<p>Or company names.</p>
<pre lang="PHP">
Apple Inc.
Google Inc.
Yahoo! Inc.
</pre>
<p>Here we can replace “ Inc.” with something else, but shorter.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </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>
<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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Relative Encoding</title>
		<link>/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/</link>
		<comments>/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 18:27:26 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Africa]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Algorithmic efficiency]]></category>
		<category><![CDATA[Application This algorithm]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[data compression algorithm]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[San Francisco]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[web server]]></category>
		<category><![CDATA[west coast]]></category>
		<category><![CDATA[Yahoo! Communications Europe Ltd.]]></category>

		<guid isPermaLink="false">/?p=2658</guid>
		<description><![CDATA[Overview Relative encoding is another data compression algorithm. While run-length encoding, bitmap encoding and diagram and pattern substitution were trying to reduce repeating data, with relative encoding the goal is a bit different. Indeed run-length encoding was searching for long runs of repeating elements, while pattern substitution and bitmap encoding were trying to “map” where &#8230; <a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Relative Encoding</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Prefix Encoding">Computer Algorithms: Data Compression with Prefix 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>Overview</h2>
<p>Relative encoding is another data compression algorithm. While <a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" title="Computer Algorithms: Data Compression with Run-length Encoding">run-length encoding</a>, <a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" title="Computer Algorithms: Data Compression with Bitmaps">bitmap encoding</a> and <a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">diagram and pattern substitution</a> were trying to reduce repeating data, with relative encoding the goal is a bit different. Indeed run-length encoding was searching for long runs of repeating elements, while pattern substitution and bitmap encoding were trying to “map” where the repetitions happen to occur. </p>
<p>The only problem with these algorithms is that not always the input stream of data is constructed out of repeating elements. It is clear that if the input stream contains many repeating elements there must be some way of reducing them. However that doesn’t mean that we cannot compress data if there are no repetitions. It all depends on the data. Let’s say we have the following stream to compress.</p>
<pre lang="PHP">
1, 2, 3, 4, 5, 6, 7
</pre>
<p>We can hardly imagine how this stream of data can be compressed. The same problem may occur when trying to compress the alphabet. Indeed the alphabet letters the very base of the words so it is the minimal part for word construction and it&#8217;s hard to compress them.</p>
<p>Fortunately this isn’t true always. An algorithm that tryies to deal with non repeating data is relative encoding. Let’s see the following input stream &#8211; years from a given decade (the 90&#8217;s).</p>
<pre lang="PHP">
1991,1991,1999,1998,1991,1993,1992,1992
</pre>
<p>Here we have 39 characters and we can reduce them. A natural approach is to remove the leading “19” as we humans often do.</p>
<pre lang="PHP">
91,91,99,98,91,93,92,92
</pre>
<p>Now we have a shorter string, but we can go even further with keeping only the first year. All other years will as relative to this year.</p>
<pre lang="PHP">
91,0,8,7,0,2,1,1
</pre>
<p>Now the volume of transferred data is reduced a lot (from 39 to 16 &#8211; more than 50%). However there are some questions we need to answer first, because the stream wont be always formatted in such pretty way. How about the next character stream?</p>
<pre lang="PHP">
91,94,95,95,98,100,101,102,105,110
</pre>
<p>We see that the value 100 is somehow in the middle of the interval and it is handy to use it as a base value for the relative encoding. Thus the stream above will become:</p>
<pre lang="PHP">
-9,-6,-5,-5,-2,100,1,2,5,10
</pre>
<p>The problem is that we can’t decide which value will be the <strong>base value</strong> so easily. What if the data was dispersed in a different way.</p>
<pre lang="PHP">
96,97,98,99,100,101,102,103,999,1000,1001,1002
</pre>
<p>Now the value of “100” isn’t useful, because compressing the stream will get something like this:</p>
<pre lang="PHP">
-4,-3,-2,-1,100,1,2,3,899,900,901,902
</pre>
<p>To group the relative values around “some” base values will be far more handy.</p>
<pre lang="PHP">
(-4,-3,-2,-1,100,1,2,3)(-1,1000,1,2)
</pre>
<p>However to decide which value will be the base value isn’t that easy. Also the encoding format is not so trivial. In the other hand this type of encoding can be useful in som specific cases as we can see bellow.<br />
<span id="more-2658"></span></p>
<h2>Implementation</h2>
<p>The implementation of this algorithm depends on the specific task and the format of the data stream. Assuming that we’ve to transfer the stream of years in JSON from a web server to a browser, here’s a short PHP snippet.</p>
<pre lang="PHP">
// JSON: [1991,1991,1999,1998,1999,1998,1995,1997,1994,1993]
$years = array(1991,1991,1999,1998,1999,1998,1995,1997,1994,1993);

function relative_encoding($input)
{
	$output = array();
	$inputLength = count($input);
	
	$base = $input[0];
	
	$output[] = $base;
	
	for ($i = 1; $i < $inputLength; $i++) {
		$output[] = $input[$i] - $base;
	}
	
	return $output;
}

// JSON: [1991,0,8,7,8,7,4,6,3,2]
echo json_encode(relative_encoding($years));
</pre>
<h2>Application</h2>
<p>This algorithm may be very useful in many cases, but here’s one of them. There are plenty of map applications around the web. Some products as <a href="http://maps.google.com/" title="Google Maps" target="_blank">Google Maps</a>, <a href="http://maps.yahoo.com/" title="Yahoo! Maps" target="_blank">Yahoo! Maps</a>, <a href="http://www.bing.com/maps/" title="Bing Maps" target="_blank">Bing Maps</a> are quite famous, while there are very useful open source projects as <a href="http://www.openstreetmap.org/" title="OpenStreetMap" target="_blank">OpenStreetMap</a>. The web sites using these apps are thousands. </p>
<p>A typical use case is to transfer lots of Geo coordinates from web server to a browser using JSON. Indeed any GEO point on Earth is relative to the point (0,0), which is located near the west coast of Africa, however on large zoom levels, when there are tons of markers we can transfer the information with relative encoding.</p>
<p>For instance the following diagram shows San Francisco with some markers on it. Their coordinates are be relative to the point (0,0) on Earth.</p>
<figure id="attachment_2682" style="width: 819px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/FullLatLononSanFrancisco.png"><img src="/wp-content/uploads/2012/01/FullLatLononSanFrancisco.png" alt="San Francisco map with full lat and lon markers" title="FullLatLononSanFrancisco" width="819" height="456" class="size-full wp-image-2682" srcset="/wp-content/uploads/2012/01/FullLatLononSanFrancisco.png 819w, /wp-content/uploads/2012/01/FullLatLononSanFrancisco-300x167.png 300w" sizes="(max-width: 819px) 100vw, 819px" /></a><figcaption class="wp-caption-text">Map markers can be relative to the (0, 0) point on Earth, which can be sometimes useless.</figcaption></figure>
<p>Far more useful may be to encode those markers, relative to the center of the city, thus we can save some space.</p>
<figure id="attachment_2681" style="width: 819px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/SanFranciscoMap.png"><img src="/wp-content/uploads/2012/01/SanFranciscoMap.png" alt="San Francisco map with relative encoded markers" title="SanFranciscoMap" width="819" height="456" class="size-full wp-image-2681" srcset="/wp-content/uploads/2012/01/SanFranciscoMap.png 819w, /wp-content/uploads/2012/01/SanFranciscoMap-300x167.png 300w" sizes="(max-width: 819px) 100vw, 819px" /></a><figcaption class="wp-caption-text">Relative encoding can be useful for map markers on large zoom level!</figcaption></figure>
<p>However this type of compression can be tricky, for example when dragging the map and updating the marker array. In the other hand we must group markers if we have to load more than one city. That’s why we must be careful when implementing it. But in the other hand it can be very useful - for instance on initial load of the map we can reduce data and speed up the load time. </p>
<p>The thing is that with relative encoding we can save only changes to base value (data) - something like version control systems and thus reducing data transfer and load. Here's a graphical example. In the first case on the diagram bellow we can see that each item is stored on its own. It doesn't depend on the adjacent items and it can be completely independent of them.</p>
<figure id="attachment_2694" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/chart_11.png"><img src="/wp-content/uploads/2012/01/chart_11.png" alt="Non-relative encoding" title="Non-relative encoding" width="600" height="371" class="size-full wp-image-2694" srcset="/wp-content/uploads/2012/01/chart_11.png 600w, /wp-content/uploads/2012/01/chart_11-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>However we can keep full info only for the first item and any other item will be relative to it, like on the diagram bellow.</p>
<figure id="attachment_2695" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/chart_21.png"><img src="/wp-content/uploads/2012/01/chart_21.png" alt="Relative encoding" title="Relative encoding" width="600" height="371" class="size-full wp-image-2695" srcset="/wp-content/uploads/2012/01/chart_21.png 600w, /wp-content/uploads/2012/01/chart_21-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Prefix Encoding">Computer Algorithms: Data Compression with Prefix 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/30/computer-algorithms-data-compression-with-relative-encoding/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
