<?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>Computing &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/computing/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: Heap and Heapsort</title>
		<link>/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/</link>
		<comments>/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/#comments</comments>
		<pubDate>Tue, 07 Aug 2012 12:33:15 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Binary heap]]></category>
		<category><![CDATA[Binary tree]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Discrete mathematics]]></category>
		<category><![CDATA[Heap]]></category>
		<category><![CDATA[Heapsort]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[next]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Priority queue]]></category>
		<category><![CDATA[purpose algorithm]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[sorting algorithm]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Tree]]></category>

		<guid isPermaLink="false">/?p=3278</guid>
		<description><![CDATA[Introduction Heapsort is one of the general sorting algorithms that performs in O(n.log(n)) in the worst-case, just like merge sort and quicksort, but sorts in place &#8211; as quicksort. Although quicksort’s worst-case sorting time is O(n2) it’s often considered that it beats other sorting algorithms in practice. Thus in practice quicksort is “faster” than heapsort. &#8230; <a href="/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Heap and Heapsort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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="/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="/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>Introduction</h2>
<p>Heapsort is one of the general sorting algorithms that performs in O(n.log(n)) in the worst-case, just like <a href="/2012/03/05/computer-algorithms-merge-sort/" title="Merge sort explained">merge sort</a> and <a href="/2012/03/13/computer-algorithms-quicksort/" title="Quicksort explained">quicksort</a>, but sorts in place &#8211; as quicksort. Although quicksort’s worst-case sorting time is O(n<sup>2</sup>) it’s often considered that it beats other sorting algorithms in practice. Thus in practice quicksort is “faster” than heapsort. In the same time developers tend to consider heapsort as more difficult to implement than other n.log(n) sorting algorithms.</p>
<p>In the other hand heapsort uses a special data structure, called heap, in order to sort items in place and this data structure is quite useful in some specific cases. Thus to understand heapsort we first need to understand what is a heap.</p>
<p>So first let&#8217;s take a look at what is a heap.</p>
<h2>Overview</h2>
<p>A heap is a complete binary tree, where all the parents are greater than their children (max heap). If all the children are greater than their parents it is considered to call the heap a min-heap. But first what is a complete binary tree? Well, this is a binary tree, where all the levels are full, except the last one, where all the items are placed on the left (just like on the image below).</p>
<p><figure id="attachment_3295" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/1.-Complete-Binary-Tree.png"><img src="/wp-content/uploads/2012/08/1.-Complete-Binary-Tree.png" alt="Complete Binary Tree" title="Complete Binary Tree" width="619" height="345" class="size-full wp-image-3295" srcset="/wp-content/uploads/2012/08/1.-Complete-Binary-Tree.png 619w, /wp-content/uploads/2012/08/1.-Complete-Binary-Tree-300x167.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">A complete binary tree is a structure where all the levels are completely full, except the last level, where all the items are placed on the left!</figcaption></figure><span id="more-3278"></span></p>
<p>Combined with the fact that each node contains a greater key than its children, a heap may look like the tree on the following diagram.</p>
<figure id="attachment_3294" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/2.-Heap.png"><img src="/wp-content/uploads/2012/08/2.-Heap.png" alt="Heap" title="Heap" width="621" height="359" class="size-full wp-image-3294" srcset="/wp-content/uploads/2012/08/2.-Heap.png 621w, /wp-content/uploads/2012/08/2.-Heap-300x173.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">In a max-heap each node contains a greater value than its children. Respectively in a min-heap each node contains a smaller value than its parent!</figcaption></figure>
<p>The thing is that if we put indices next to each node of this tree, starting from the root (index 1) and continuing from left to right on each level, we’ll get the following tree.</p>
<figure id="attachment_3293" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/3.-Heap-Indexes.png"><img src="/wp-content/uploads/2012/08/3.-Heap-Indexes.png" alt="Heap Indices" title="Heap Indices" width="618" height="360" class="size-full wp-image-3293" srcset="/wp-content/uploads/2012/08/3.-Heap-Indexes.png 618w, /wp-content/uploads/2012/08/3.-Heap-Indexes-300x174.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Putting indices right to each node reveals the secret of the heap. The i-th node has left child exactly with the index 2*i, and right child with index 2*i+1! This is a great opportunity to put this tree into an array!</figcaption></figure>
<p>Now if we take a closer look to the picture above we can see that the indices of a node and its children are closely related. Thus for a node of an index <em>i</em> we see that its left child has the index <em>2*i</em>, while its right child’s index is <em>2*i + 1</em>.</p>
<p><em>This particular order gives us the possibility to store each heap in an array.</em></p>
<figure id="attachment_3292" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/4.-Heap-as-an-Array.png"><img src="/wp-content/uploads/2012/08/4.-Heap-as-an-Array.png" alt="Heap as an Array" title="Heap as an Array" width="620" height="399" class="size-full wp-image-3292" srcset="/wp-content/uploads/2012/08/4.-Heap-as-an-Array.png 620w, /wp-content/uploads/2012/08/4.-Heap-as-an-Array-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The heap tree can be easily represented as an array!</figcaption></figure>
<p>Since in a heap its greater element is in the root of the tree (for max-heap, respectively in a min-heap its smallest element is the root) we need to answer two questions. </p>
<ol>
<li>How to build a heap out of an ordinary array?</li>
<li>After extracting the root, which is the greatest (smallest) item, how can we rebuild the heap in order to keep it a heap again?</li>
</ol>
<p>First let’s try to answer the first question. How to build a heap? Well, let’s forget about the array for a while and let’s take a look on a ordinary binary tree with only three nodes.</p>
<figure id="attachment_3291" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/5.-Heapify.png"><img src="/wp-content/uploads/2012/08/5.-Heapify.png" alt="Heapify" title="Heapify" width="620" height="317" class="size-full wp-image-3291" srcset="/wp-content/uploads/2012/08/5.-Heapify.png 620w, /wp-content/uploads/2012/08/5.-Heapify-300x153.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Fixing a node and its children in order to form a valid Heap is often called heapify!</figcaption></figure>
<p>We see that the three green nodes destroy the structure of our heap, because the root (1) is smaller than its children (4) and (5). Thus we need to fix this problem and what we’re going to do is to swap the root with its biggest child. </p>
<figure id="attachment_3290" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/6.-Heapify-Part-1.png"><img src="/wp-content/uploads/2012/08/6.-Heapify-Part-1.png" alt="Heapify Part 2" title="Heapify Part 2" width="620" height="399" class="size-full wp-image-3290" srcset="/wp-content/uploads/2012/08/6.-Heapify-Part-1.png 620w, /wp-content/uploads/2012/08/6.-Heapify-Part-1-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We first need to know which is the greatest out of the three items, than in case it is not the root, swap its value with the root!</figcaption></figure>
<p>As you can see on the picture above the <em>i</em>-th item is first compared to its left child. The greater of these two items is compared to the right child. Note that we don’t swap them &#8211; we just compare them to get which one is greater. Once we find the greatest of these three values we swap them with the root in case it&#8217;s not the root value.</p>
<p>Although now these three elements form a heap, by swapping the root with one of its children may destroy the heap constructed out of this child. That is why we continue the same procedure with it.</p>
<p>This actually gives us the procedure to heapify the three nodes constructed out of the <em>i</em>-th item and its children. However to build a heap from an arbitrary array we should perform this operation starting from floor(len[A] / 2) down to the first item in the array.</p>
<figure id="attachment_3289" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/7.-Random-Array-to-Heap.png"><img src="/wp-content/uploads/2012/08/7.-Random-Array-to-Heap.png" alt="Random Array to Heap" title="Random Array to Heap" width="620" height="399" class="size-full wp-image-3289" srcset="/wp-content/uploads/2012/08/7.-Random-Array-to-Heap.png 620w, /wp-content/uploads/2012/08/7.-Random-Array-to-Heap-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Building a random array into a heap isn&#8217;t that difficult since we know that half of the complete tree items lay in it&#8217;s lowest level! Thus we start from floor(len[A] / 2)!</figcaption></figure>
<p>Why? Well, a complete binary tree with a full last level contains n/2 + 1 nodes in it. They don’t have children, thus we don’t need to check them &#8211; they are &#8220;sorted&#8221;. Indeed if we start from an item on the right of floor(len[A] / 2) there won’t be items with indices <em>2*i</em> and <em>2*i + 1</em>.</p>
<h2>Code</h2>
<p>So far we know how to build the heap. Next thing is to swap the first and the last element of the array and rebuild the heap. Here’s the PHP code of how to do this.</p>
<pre lang="PHP">
$a = array(1, 6, 3, 8, 2, 5, 4);

function heapify(&$a, &$i, &$heap_size)
{
    $l = $i*2 + 1;
    $r = $i*2 + 2;
    
    if ($l < $heap_size &#038;&#038; $a[$i] < $a[$l]) {
        $largest = $l;
    } else {
        $largest = $i;
    }
    
    if ($r < $heap_size &#038;&#038; $a[$largest] < $a[$r]) {
        $largest = $r;
    }
    
    if ($largest != $i) {
        $t = $a[$i];
        $a[$i] = $a[$largest];
        $a[$largest] = $t;
        
        heapify($a, $largest, $heap_size);
    }
}

function build_heap(&#038;$a, &#038;$heap_size)
{
    $len = floor($heap_size / 2);
    for ($i = $len; $i > -1; $i--) {
        heapify($a, $i, $heap_size);
    }
}

function heapsort(&$a)
{
    $heap_size = count($a);
    build_heap($a, $heap_size);
    
    while ($heap_size--) {
        $t = $a[$heap_size];
        $a[$heap_size] = $a[0];
        $a[0] = $t;
        build_heap($a, $heap_size);
    }
}

// 1 2 3 4 5 6 8
heapsort($a);
</pre>
<h2>Complexity</h2>
<p>OK, the last question is &#8211; how do we know that this algorithm sorts in place in n.log(n) time? Let’s explore the algorithm one more time. The heapify worst-case is when we start from the root down to the lowest level of the tree. In these terms if the tree height is <strong>h</strong>, the time is O(h), but because the tree is balanced (complete) the time in terms of n is O(log(n)). </p>
<p>In the other hand to build a heap we walk from floor(len[A] / 2) to 0, which makes it run in O(n.log(n)). However there is only one case when the heapify may run in log(n), and that is when it starts from the root, so it’s not absolutely true that building the heap runs in n.log(n).</p>
<p>Indeed heapify depend on the level it has been started. It doesn’t run for the last ceil(n/2) items and it runs in O(1) for another 2<sup>h-1</sup>. Thus in practice we can build a heap in O(n). </p>
<p>Once we have the heap built, the only thing to do is to extract its first element and rebuild &#8211; heapify from the first item. This makes the sorting algorithm run in O(n.log(n)) &#8211; just like quicksort and mergesort.</p>
<h2>Application</h2>
<p>As I said in the beginning of this post quicksort is often the fastest general purpose algorithm in practice. This makes both merge sort and heapsort not so popular. However heapsort introduces an interesting data structure which can help us in many other cases. </p>
<p>It’s initially used to implement priority queues. What is great about a heap is that after we build it, which we know how to do in linear time, we can extract the greatest value &#8211; thus taking the highest priority task. Then with rebuilding the heap we can extract the next priority and so on, without fully sorting the array. </p>
<p>This makes the heapsort the only sorting algorithm that can sort the first <strong>k</strong> items out of a set of <strong>n</strong> items without sorting the whole set.</p>
<p>Indeed let’s say we have a set of positive integers and we’d like to get the biggest sum out of three items. Obviously we can sort the array and take the greatest three numbers, but this will cost us n.log(n) time, while using heapsort we can do it much faster! And all this without extra space &#8211; in place!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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="/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="/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/08/07/computer-algorithms-heap-and-heapsort-data-structure/feed/</wfw:commentRss>
		<slash:comments>7</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>PHP Strings Don&#8217;t Need Quotes</title>
		<link>/2012/04/26/php-strings-dont-need-quotes/</link>
		<comments>/2012/04/26/php-strings-dont-need-quotes/#comments</comments>
		<pubDate>Thu, 26 Apr 2012 13:52:53 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Cross-platform software]]></category>
		<category><![CDATA[Curly bracket programming languages]]></category>
		<category><![CDATA[PHP interpreter]]></category>
		<category><![CDATA[PHP programming language]]></category>
		<category><![CDATA[Procedural programming languages]]></category>
		<category><![CDATA[Programming language]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[Social Issues]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">/?p=3017</guid>
		<description><![CDATA[I bet you didn&#8217;t know that PHP strings don&#8217;t need quotes! Indeed PHP developers work with strings with either single or double quotes, but actually in some cases you don&#8217;t need them. PHP by Book Here&#8217;s how PHP developer declare a string, which is something very common in any programming language. $my_var = 'hello world'; &#8230; <a href="/2012/04/26/php-strings-dont-need-quotes/" class="more-link">Continue reading <span class="screen-reader-text">PHP Strings Don&#8217;t Need Quotes</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/07/12/a-javascript-trick-you-should-know/" rel="bookmark" title="A JavaScript Trick You Should Know">A JavaScript Trick You Should Know </a></li>
<li><a href="/2010/03/10/php-if-else-endif-statements/" rel="bookmark" title="PHP if-else-endif Statements">PHP if-else-endif Statements </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>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>I bet you didn&#8217;t know that PHP strings don&#8217;t need quotes! Indeed PHP developers work with strings with either single or double quotes, but actually in some cases you don&#8217;t need them.</p>
<h2>PHP by Book</h2>
<p>Here&#8217;s how PHP developer declare a string, which is something very common in any programming language.</p>
<pre lang="PHP">
$my_var = 'hello world';
// or
$my_var = "hello world";
</pre>
<h2>PHP Tricks</h2>
<p>What if you do the following:</p>
<pre lang="PHP">
echo hello;
</pre>
<p>That appears to be correct &#8230; Well, it&#8217;s not absolutely correct. You&#8217;ll be &#8220;noticed&#8221;.</p>
<pre lang="PHP">
// Notice: Use of undefined constant hello
echo hello;
</pre>
<p>However if you disable error reporting, the code will be completely fine.</p>
<pre lang="PHP">
error_reporting(0);

// no problem now
echo hello;
</pre>
<h2>Variations</h2>
<p>What follows from the thing above is that you can use strings without quotes:</p>
<pre lang="PHP">
// hello
echo hello;

// hello world (concatenated)
echo hello . ' world';

// helloworld
echo hello . world;
</pre>
<p>However you can&#8217;t have spaces and most of the &#8220;special&#8221; symbols.</p>
<pre lang="PHP">
// syntax error
echo hello world;

// syntax error
echo hello!;
</pre>
<h2>Final Words</h2>
<p>Although you can do this in PHP, that is completely wrong. The code becomes more difficult to read and understand. In the second place you can miss a $ sign in front of a variable declaration and thus the PHP interpreter will assume this is a string. So disable error reporting isn&#8217;t so great sometimes.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/07/12/a-javascript-trick-you-should-know/" rel="bookmark" title="A JavaScript Trick You Should Know">A JavaScript Trick You Should Know </a></li>
<li><a href="/2010/03/10/php-if-else-endif-statements/" rel="bookmark" title="PHP if-else-endif Statements">PHP if-else-endif Statements </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>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/26/php-strings-dont-need-quotes/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Boyer-Moore String Searching</title>
		<link>/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/</link>
		<comments>/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/#comments</comments>
		<pubDate>Tue, 17 Apr 2012 08:24:46 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Boyer–Moore string search algorithm]]></category>
		<category><![CDATA[Boyer–Moore–Horspool algorithm]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[J Strother Moore]]></category>
		<category><![CDATA[Morris-Pratt algorithm]]></category>
		<category><![CDATA[natural language search]]></category>
		<category><![CDATA[pattern forward]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Rabin-Karp algorithm]]></category>
		<category><![CDATA[Rabin-Karp string search algorithm]]></category>
		<category><![CDATA[Robert S. Boyer]]></category>
		<category><![CDATA[search]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[String searching algorithm]]></category>
		<category><![CDATA[string searching algorithms]]></category>
		<category><![CDATA[Strlen]]></category>
		<category><![CDATA[Substring]]></category>

		<guid isPermaLink="false">/?p=3049</guid>
		<description><![CDATA[Introduction Have you ever asked yourself which is the algorithm used to find a word after clicking Ctrl+F and typing something? Well I guess you know the answer from the title, but in this article you’ll find out how exactly this is done. As we saw from the Morris-Pratt string searching we don’t need to &#8230; <a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Boyer-Moore String Searching</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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/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/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Have you ever asked yourself which is the algorithm used to find a word after clicking Ctrl+F and typing something? Well I guess you know the answer from the title, but in this article you’ll find out how exactly this is done.</p>
<p>As we saw from the <a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" title="Computer Algorithms: Morris-Pratt String Searching">Morris-Pratt string searching</a> we don’t need to compare the text and the pattern character by character. Some comparisons can be skipped in order to improve the performance of the string searching. Indeed the <a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" title="Computer Algorithms: Brute Force String Matching">brute force string searching</a> and the <a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" title="Computer Algorithms: Rabin-Karp String Searching">Rabin-Karp algorithm</a> are quite slow only because they compare the pattern and the text character by character.</p>
<p>In the other hand the Morris-Pratt algorithm is a very good improvement of the brute force string searching, but the question remains. Is there any algorithm that is faster than Morris-Pratt &#8211; is there any way to skip more comparisons and to move the pattern faster.</p>
<p>It’s clear that if we have to find whether a single character is contained into a text we need at least &#8220;n&#8221; steps, where n is the length of the text. Once we have to find whether a pattern with the length of &#8220;m&#8221; is contained into a text with length of &#8220;n&#8221; the case is getting a little more complex.</p>
<p>However the answer is that there is such algorithm that is faster and more suitable than Morris-Pratt. This is the Boyer-Moore string searching.</p>
<h2>Overview</h2>
<p>Boyer-Moore is an algorithm that improves the performance of pattern searching into a text by considering some observations. It is defined in 1977 by <a href="http://en.wikipedia.org/wiki/Robert_S._Boyer" title="Robert S. Boyer" target="_blank">Robert S. Boyer</a> and <a href="http://en.wikipedia.org/wiki/J_Strother_Moore" title="J Strother Moore" target="_blank">J Strother Moore</a> and it consist of some specific features. </p>
<p>First of all this algorithm starts comparing the pattern from the leftmost part of text and moves it to the right, as on the picture below.</p>
<p><figure id="attachment_3059" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreShiftingDirection.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreShiftingDirection.png" alt="Boyer-Moore Shifting Direction" title="Boyer-Moore Shifting Direction" width="618" height="153" class="size-full wp-image-3059" srcset="/wp-content/uploads/2012/04/Boyer-MooreShiftingDirection.png 618w, /wp-content/uploads/2012/04/Boyer-MooreShiftingDirection-300x74.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">In Boyer-Moore the pattern is shifted from left to right!</figcaption></figure><span id="more-3049"></span></p>
<p>Unlike other string searching algorithms though, Boyer-Moore compares the pattern against a possible match from right to left as shown below.</p>
<figure id="attachment_3066" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreComparisonModel.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreComparisonModel.png" alt="Boyer-Moore Comparison Model" title="Boyer-Moore Comparison Model" width="622" height="169" class="size-full wp-image-3066" srcset="/wp-content/uploads/2012/04/Boyer-MooreComparisonModel.png 622w, /wp-content/uploads/2012/04/Boyer-MooreComparisonModel-300x81.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">Unlike other algorithms the letters of the pattern are compared from right to left!</figcaption></figure>
<p>The main idea of Boyer-Moore in order to improve the performance are some observations of the pattern. In the terminology of this algorithm they are called good-suffix and bad-character shifts. Let’s see by the following examples what they are standing for.</p>
<h3>Good-suffix Shifts</h3>
<p>Just like the Morris-Pratt algorithm we start to compare the pattern against some portion of the text where a possible match will occur. In Boyer-Moore as I said this is done from the rightmost letter of the pattern. After some characters have matched we find a mismatch.</p>
<figure id="attachment_3065" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreAMismatch.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreAMismatch.png" alt="Boyer-Moore a Mismatch" title="Boyer-Moore a Mismatch" width="622" height="214" class="size-full wp-image-3065" srcset="/wp-content/uploads/2012/04/Boyer-MooreAMismatch.png 622w, /wp-content/uploads/2012/04/Boyer-MooreAMismatch-300x103.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>So how can we move the pattern to the right in order to skip unusual comparisons. To answer this question we need to explore the pattern. Let’s say there is a portion of the pattern that is repeated inside the pattern itself, like it is shown on the picture below.</p>
<figure id="attachment_3062" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1.png" alt="Boyer-Moore Good-suffix Shift 1" title="Boyer-Moore Good-suffix Shift 1" width="622" height="195" class="size-full wp-image-3062" srcset="/wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1.png 622w, /wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1-300x94.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">The pattern may consist of repeating portions of characters!</figcaption></figure>
<p>In this case we must move the pattern thus the repeated portion must now align with its first occurrence in the pattern.</p>
<p>A variation of this case is when the portion from the pattern A overlaps with another portion that consists of the same characters.</p>
<figure id="attachment_3061" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2.png" alt="Boyer-Moore Good Suffix Shift 2" title="Boyer-Moore Good Suffix Shift 2" width="622" height="195" class="size-full wp-image-3061" srcset="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2.png 622w, /wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2-300x94.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">Sometimes these portions may overlap!</figcaption></figure>
<p>Yet again the shift must align the second portion with its first occurrence. </p>
<p>Finally only a portion of A, let’s say &#8220;B&#8221;, can happen to occur in the very beginning of the pattern, as on the diagram below.</p>
<figure id="attachment_3060" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3.png" alt="Boyer-Moore Good Suffix Shift 3" title="Boyer-Moore Good Suffix Shift 3" width="622" height="195" class="size-full wp-image-3060" srcset="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3.png 622w, /wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3-300x94.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">Only a sub-string of the pattern may re-occur at its front!</figcaption></figure>
<p>Now we must align the left end of the pattern with the rightmost occurrence of &#8220;B&#8221;.</p>
<h3>Bad Character Shifts</h3>
<p>Beside the good-suffix shifts the Boyer-Moore algorithm make use of the so called bad-character shifts. In case of a mismatch we can skip comparisons in case the character in the text doesn’t happen to appear in the pattern. To become clearer let’s see the following examples.</p>
<figure id="attachment_3064" style="width: 623px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter1.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter1.png" alt="Boyer-Moore Bad Character 1" title="Boyer-Moore Bad Character 1" width="623" height="237" class="size-full wp-image-3064" srcset="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter1.png 623w, /wp-content/uploads/2012/04/Boyer-MooreBadCharacter1-300x114.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></a><figcaption class="wp-caption-text">If the mismatched letter of the text appears in the pattern only in its front we can align it easily!</figcaption></figure>
<p>In the picture above we see that the mismatched character &#8220;B&#8221; from the text appears only in the beginning of the pattern. Thus we can simply shift the pattern to the right and align both characters B, skipping comparisons. An even better case is described by the following diagram where the mismatched letter isn’t contained into the pattern at all. Then we can shift forward the whole pattern.</p>
<figure id="attachment_3063" style="width: 623px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter2.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter2.png" alt="Boyer-Moore Bad Character 2" title="Boyer-Moore Bad Character 2" width="623" height="237" class="size-full wp-image-3063" srcset="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter2.png 623w, /wp-content/uploads/2012/04/Boyer-MooreBadCharacter2-300x114.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></a><figcaption class="wp-caption-text">In case the mismatched letter isn&#039;t contained into the pattern we move forward the pattern!</figcaption></figure>
<h3>Maximum of Good-suffix and Bad-Character shifts</h3>
<p>Boyer-Moore needs both good-suffix and bad-character shifts in order to speed up searching performance. After a mismatch the maximum of both is considered in order to move the pattern to the right.</p>
<h2>Complexity</h2>
<p>It&#8217;s clear that Boyer-Moore is faster than Morris-Pratt, but actually its worst-case complexity is O(n+m). The thing is that in natural language search Boyer-Moore does pretty well.</p>
<figure id="attachment_3073" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-Moore-Complexity.png"><img src="/wp-content/uploads/2012/04/Boyer-Moore-Complexity.png" alt="Boyer-Moore Complexity" title="Boyer-Moore Complexity" width="600" height="371" class="size-full wp-image-3073" srcset="/wp-content/uploads/2012/04/Boyer-Moore-Complexity.png 600w, /wp-content/uploads/2012/04/Boyer-Moore-Complexity-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">Worst-case scenario of Boyer-Moore - O(m+n)</figcaption></figure>
<h2>Implementation</h2>
<p>Finally let’s see the implementation in <a href="/category/php/" title="PHP on stoimen.com">PHP</a>, which can be easily &#8220;transcribed&#8221; into any other programming language. The only thing we need is the structures for bad-character shifts and good-suffixes shifts.</p>
<pre lang="PHP">
<?php

/**
 * Pattern we're searching for
 *
 * @var string
 */
$pattern = 'gloria';

/**
 * The text we're searching in
 *
 * @var string
 */
$text = 'Sic transit gloria mundi, non transit gloria Gundi!';

/**
 * Calculates the suffixes for a given pattern
 *
 * @param string $pattern
 * @param array  $suffixes
 */
function suffixes($pattern, &#038;$suffixes)
{
   $m = strlen($pattern);

   $suffixes[$m - 1] = $m;
   $g = $m - 1;

   for ($i = $m - 2; $i >= 0; --$i) {
      if ($i > $g && $suffixes[$i + $m - 1 - $f] < $i - $g) {
         $suffixes[$i] = $suffixes[$i + $m - 1 - $f];
      } else {
         if ($i < $g) {
            $g = $i;
         }
         $f = $i;
         	
         while ($g >= 0 && $pattern[$g] == $pattern[$g + $m - 1 - $f]) {
            $g--;
         }
         $suffixes[$i] = $f - $g;
      }
   }
}

/**
 * Fills in the array of bad characters.
 *
 * @param string $pattern
 * @param array  $badChars
 */
function badCharacters($pattern, &$badChars)
{
   $m = strlen($pattern);

   for ($i = 0; $i < $m - 1; ++$i) {
      $badChars[$pattern{$i}] = $m - $i - 1;
   }
}

/**
 * Fills in the array of good suffixes
 *
 * @param string $pattern
 * @param array  $goodSuffixes
 */
function goodSuffixes($pattern, &#038;$goodSuffixes)
{
   $m 		= strlen($pattern);
   $suff 	= array();

   suffixes($pattern, $suff);

   for ($i = 0; $i < $m; $i++) {
      $goodSuffixes[$i] = $m;
   }

   for ($i = $m - 1; $i >= 0; $i--) {
      if ($suff[$i] == $i + 1) {
         for ($j = 0; $j < $m - $i - 1; $j++) {
            if ($goodSuffixes[$j] == $m) {
               $goodSuffixes[$j] = $m - $i - 1;
            }
         }
      }
   }

   for ($i = 0; $i < $m - 2; $i++) {
      $goodSuffixes[$m - 1 - $suff[$i]] = $m - $i - 1;
   }
}

/**
 * Performs a search of the pattern into a given text
 *
 * @param string $pattern
 * @param string $text
 */
function boyer_moore($pattern, $text)
{
   $n = strlen($text);
   $m = strlen($pattern);

   $goodSuffixes 	= array();
   $badCharacters 	= array();

   goodSuffixes($pattern, &#038;$goodSuffixes);
   badCharacters($pattern, &#038;$badCharacters);

   $j = 0;
   while ($j < $n - $m) {
      for ($i = $m - 1; $i >= 0 && $pattern[$i] == $text[$i + $j]; $i--);
      if ($i < 0) {
         // note that if the substring occurs more
         // than once into the text, the algorithm will
         // print out each position of the substring
         echo $j;
         $j += $goodSuffixes[0];
      } else {
         $j += max($goodSuffixes[$i], $badCharacters[$text[$i + $j]] - $m + $i + 1);
      }
   }
}

// search using Boyer-Moore
// will return 12 and 38
boyer_moore($pattern, $text);
</pre>
<h2>Application</h2>
<p>Boyer-Moore is one of the most used string searching algorithm in practice. It is intuitively clear where it can be useful, but yet again I’ll say only that this algorithm is considered as the mostly used in practice for search and replace operations in text editors.</p>
<figure id="attachment_3068" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreApplication.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreApplication.png" alt="Boyer-Moore Application" title="Boyer-Moore Application" width="620" height="399" class="size-full wp-image-3068" srcset="/wp-content/uploads/2012/04/Boyer-MooreApplication.png 620w, /wp-content/uploads/2012/04/Boyer-MooreApplication-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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/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/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/feed/</wfw:commentRss>
		<slash:comments>21</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>jQuery UI Slider IE bugfix</title>
		<link>/2012/02/16/jquery-ui-slider-ie-bugfix/</link>
		<comments>/2012/02/16/jquery-ui-slider-ie-bugfix/#respond</comments>
		<pubDate>Thu, 16 Feb 2012 10:30:26 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[Null]]></category>
		<category><![CDATA[Slider]]></category>
		<category><![CDATA[Widgets]]></category>

		<guid isPermaLink="false">/?p=2718</guid>
		<description><![CDATA[Do your jQuery slider brakes under IE too? When you want to null the sliders on an page, using jQuery UI Slider, somehow the following code works in any browser except IE. // wrong $('.my-slider').slider('value', 0); I say somehow, because according to the documentation this code is simply wrong. It can be used to get &#8230; <a href="/2012/02/16/jquery-ui-slider-ie-bugfix/" class="more-link">Continue reading <span class="screen-reader-text">jQuery UI Slider IE bugfix</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/06/22/jquery-get-the-selected-option-text/" rel="bookmark" title="jQuery: Get the Selected Option Text">jQuery: Get the Selected Option Text </a></li>
<li><a href="/2010/02/01/writing-a-jquery-plugin-part-2-sample-plugin/" rel="bookmark" title="Writing a jQuery plugin &#8211; (part 2). Sample plugin.">Writing a jQuery plugin &#8211; (part 2). Sample plugin. </a></li>
<li><a href="/2011/04/05/jquery-unbind/" rel="bookmark" title="jQuery.unbind()">jQuery.unbind() </a></li>
<li><a href="/2009/10/21/event-driven-programming-with-jquery-part-2-events-in-jquery/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 2). Events in jQuery.">Event driven programming with jQuery &#8211; (part 2). Events in jQuery. </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Do your jQuery slider brakes under IE too?</h2>
<p>When you want to null the sliders on an page, using jQuery UI Slider, somehow the following code works in any browser except IE.</p>
<pre lang="javascript">
// wrong
$('.my-slider').slider('value', 0);
</pre>
<p>I say somehow, because according to the documentation this code is simply wrong. It can be used to get the value of the slider as it is a getter. You can null the value with the following snippet.</p>
<pre lang="javascript">
// correct
$('.my-slider').slider('option', 'value', 0);
</pre>
<h2>IE Fix</h2>
<p>Another way to null the value is with an anonymous object.</p>
<pre lang="javascript">
// correct
$('.my-slider').slider({ value: 0 });
</pre>
<p>This works on every browser including IE.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/06/22/jquery-get-the-selected-option-text/" rel="bookmark" title="jQuery: Get the Selected Option Text">jQuery: Get the Selected Option Text </a></li>
<li><a href="/2010/02/01/writing-a-jquery-plugin-part-2-sample-plugin/" rel="bookmark" title="Writing a jQuery plugin &#8211; (part 2). Sample plugin.">Writing a jQuery plugin &#8211; (part 2). Sample plugin. </a></li>
<li><a href="/2011/04/05/jquery-unbind/" rel="bookmark" title="jQuery.unbind()">jQuery.unbind() </a></li>
<li><a href="/2009/10/21/event-driven-programming-with-jquery-part-2-events-in-jquery/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 2). Events in jQuery.">Event driven programming with jQuery &#8211; (part 2). Events in jQuery. </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/02/16/jquery-ui-slider-ie-bugfix/feed/</wfw:commentRss>
		<slash:comments>0</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>
		<item>
		<title>JavaScript Performance: for vs. while</title>
		<link>/2012/01/24/javascript-performance-for-vs-while/</link>
		<comments>/2012/01/24/javascript-performance-for-vs-while/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 14:20:05 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Control flow]]></category>
		<category><![CDATA[firebug]]></category>
		<category><![CDATA[Increment]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[software/hardware]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[While loop]]></category>

		<guid isPermaLink="false">/?p=2635</guid>
		<description><![CDATA[JavaScript Loops If you have read some preformance tests on JavaScript loops, you may have heard that &#8220;while&#8221; is faster than &#8220;for&#8221;. However the question is how faster is &#8220;while&#8221;? Here are some results, but first let&#8217;s take a look on the JavaScript code. The for experiment console.time('for'); for (var i = 0; i < &#8230; <a href="/2012/01/24/javascript-performance-for-vs-while/" class="more-link">Continue reading <span class="screen-reader-text">JavaScript Performance: for vs. while</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/02/02/firebugs-console-time-accuracy/" rel="bookmark" title="Firebug&#8217;s console.time() accuracy">Firebug&#8217;s console.time() accuracy </a></li>
<li><a href="/2010/02/02/profiling-javascript-with-firebug-console-profile-console-time/" rel="bookmark" title="Profiling JavaScript with Firebug. console.profile() &#038; console.time()!">Profiling JavaScript with Firebug. console.profile() &#038; console.time()! </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/06/02/detecting-pressed-key-with-e-which-in-javascript/" rel="bookmark" title="Detecting Pressed Key with e.which in JavaScript">Detecting Pressed Key with e.which in JavaScript </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>JavaScript Loops</h2>
<p>If you have read some preformance tests on JavaScript loops, you may have heard that &#8220;while&#8221; is faster than &#8220;for&#8221;. However the question is how faster is &#8220;while&#8221;? Here are some results, but first let&#8217;s take a look on the JavaScript code. </p>
<h4>The <strong>for</strong> experiment</h4>
<pre lang="javascript">
console.time('for');
for (var i = 0; i < 10000000; i++) {
	i / 2;
}
console.timeEnd('for');
</pre>
<h4>The <strong>while</strong> experiment</h4>
<pre lang="javascript">
console.time('while');
var i = 0;
while (i++ < 10000000) {
	i / 2;
}
console.timeEnd('while');
</pre>
<p>Note - these tests are performed and measured with Firebug on Firefox.</p>
<h2>Results</h2>
<p>It's a fact, that you'll get different results as many times as you run this snippet. It depends also on the enviroment and software/hardware specs. That is why I performed them 10 times and then I took the average value. Here are the values of my performance tests. Note that both <strong>for</strong> and <strong>while</strong> perform 10,000,000 iterations.</p>
<p><iframe width='576' height='263' frameborder='0' src='https://docs.google.com/spreadsheet/pub?hl=en_US&#038;hl=en_US&#038;key=0Avxdu4aY4-UGdDktZEJHYUh5RWFLd1prOG52dDdTdUE&#038;single=true&#038;gid=0&#038;output=html&#038;widget=true'></iframe></p>
<h2>And the Winner Is</h2>
<p><strong>While</strong> is the winner with an average result of 83.5 milliseconds, while "for" result is 88 average milliseconds.</p>
<p>As the diagram bellow shows, <strong>the while loop is slightly faster</strong>. However we should be aware that these performance gains are significant for large number of iterations!</p>
<figure id="attachment_2668" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/chart_1-1.png"><img src="/wp-content/uploads/2012/01/chart_1-1.png" alt="JavaScript Performance: for vs. while" title="JavaScript Performance: for vs. while" width="600" height="371" class="size-full wp-image-2668" srcset="/wp-content/uploads/2012/01/chart_1-1.png 600w, /wp-content/uploads/2012/01/chart_1-1-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">JavaScript Performance: for vs. while</figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/02/02/firebugs-console-time-accuracy/" rel="bookmark" title="Firebug&#8217;s console.time() accuracy">Firebug&#8217;s console.time() accuracy </a></li>
<li><a href="/2010/02/02/profiling-javascript-with-firebug-console-profile-console-time/" rel="bookmark" title="Profiling JavaScript with Firebug. console.profile() &#038; console.time()!">Profiling JavaScript with Firebug. console.profile() &#038; console.time()! </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/06/02/detecting-pressed-key-with-e-which-in-javascript/" rel="bookmark" title="Detecting Pressed Key with e.which in JavaScript">Detecting Pressed Key with e.which in JavaScript </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/24/javascript-performance-for-vs-while/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution</title>
		<link>/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/</link>
		<comments>/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/#respond</comments>
		<pubDate>Mon, 23 Jan 2012 14:58:48 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Coding theory]]></category>
		<category><![CDATA[Computer file formats]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[conventional compressing tool]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[Information theory]]></category>
		<category><![CDATA[Lossy compression]]></category>
		<category><![CDATA[pattern substitution algorithm]]></category>
		<category><![CDATA[pattern substitution algorithms]]></category>
		<category><![CDATA[Pattern Substitution The pattern substitution algorithm]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[web hosting]]></category>

		<guid isPermaLink="false">/?p=2623</guid>
		<description><![CDATA[Overview Two variants of run-length encoding are the diagram encoding and the pattern substitution algorithms. The diagram encoding is actually a very simple algorithm. Unlike run-length encoding, where the input stream must consists of many repeating elements, as “aaaaaaaa” for instance, which are very rare in a natural language, there are many so called “diagrams” &#8230; <a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution</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/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/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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>Two variants of <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> are the diagram encoding and the pattern substitution algorithms. The diagram encoding is actually a very simple algorithm. Unlike run-length encoding, where the input stream must consists of many repeating elements, as <strong>“aaaaaaaa”</strong> for instance, which are very rare in a natural language, there are many so called “diagrams” in almost any natural language. In plain English there are some diagrams as <strong>“the”</strong>, <strong>“and”</strong>, <strong>“ing”</strong> (in the word “waiting” for example), <strong>“ a”</strong>, <strong>“ t”</strong>, <strong>“ e”</strong> and many doubled letters. Actually we can extend those diagrams by adding surrounding spaces. Thus we can encode not only “the”, but “ the “, which are 5 characters (2 spaces and 3 letters) with something shorter. In the other hand, as I said, in plain English there are two many doubled letters, which unfortunately aren’t something special for run-length encoding and the compression ratio will be small. Even worse the encoded text may happen to be longer than the input message. Let’s see some examples.</p>
<p>Let’s say we’ve to encode the message “successfully accomplished”, which consists of four doubled letters. However to compress it with run-length encoding we’ll need at least 8 characters, which doesn’t help us a lot.</p>
<pre>
// 8 chars replaced by 8 chars!?
input: 	"successfully accomplished"
output:	"su2ce2sfu2ly a2complished"
</pre>
<p>The problem is that if the input text contains numbers, “2” in particular, we’ve to chose an escape symbol (“@” for example), which we’ll use to mark where the encoded run begins. Thus if the input message is “2 successfully accomplished tasks”, it will be encoded as “2 su@2ce@2sfu@2ly a@2complished tasks”. Now the output message is longer!!! than the input string.</p>
<pre>
// the compressed message is longer!!!
input:	"2 successfully accomplished"
output:	"2 su@2ce@2sfu@2ly a@2complished tasks"
</pre>
<p>Again if the input stream contains the escape symbol, we have to find another one, and the problem is that it is often too difficult to find short escape symbol that doesn’t appear in the input text, without a full scan of the text.<span id="more-2623"></span></p>
<p>That is why run-length encoding isn’t a good solution when compressing plain text, where long runs rarely appear. Well, of course, there are exceptions. For example such an exception is the lossy text compression with run-length encoding. It is intuitively clear that compressing text with loss is rarely useful, especially when you’ve to decompress exactly the same text. However there are some cases that lossy compression may be useful. Such case can be removing spaces. Indeed the text <strong>“successfully      accomplished”</strong> brings us exactly the same information as <strong>“successfully accomplished”</strong>. In this case we can simply remove those spaces. Indeed we can use a marker to indicate the long run of spaces like <strong>“successfully@6 accomplished”</strong> in order to decompress the input string with absolutely no loss, but we can also throw those symbols away. This desision depends on the goal. Exactly with the same goal in mind we can remove new lines and tabs, only if we’re sure that the sense of the text is preserved. Yet again, a problem is that such long runs don’t happen to occur in random texts. That is why it’s better to use diagram encoding for plain text compression instead of run-length encoding.</p>
<h2>Few Questions</h2>
<p>After understanding the principles of the diagram encoding, let’s see some examples. In the example above it is better to replace doubled letters with something shorter. Let’s say # for “cc”, @ for “ss” and % for “ll”. Thus the input text will be compressed as “su#e@fu%y a#omplished”,  which is shorter. But yet again what will happen if the input message contains one of the substitutions? Also we can’t say if there are many doubled letters and enough reasonable substitutions for them. A better approach is to replace patterns. </p>
<figure id="attachment_2640" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/DiagramEncodingonTexts.png"><img src="/wp-content/uploads/2012/01/DiagramEncodingonTexts.png" alt="Compressing texts with diagram encoding" title="Compressing texts with diagram encoding" width="620" class="size-full wp-image-2640" srcset="/wp-content/uploads/2012/01/DiagramEncodingonTexts.png 683w, /wp-content/uploads/2012/01/DiagramEncodingonTexts-300x128.png 300w" sizes="(max-width: 683px) 100vw, 683px" /></a><figcaption class="wp-caption-text">Run-length encoding isn&#039;t a good approach for text compression, because long runs rarely appear in a natural language.</figcaption></figure>
<h2>Pattern Substitution</h2>
<p>The pattern substitution algorithm is a variant of the diagram encoding. As I said above in plain English a very commonly used pattern can be “ the “, which is five characters long. We can now replace it with something like “$%” for example. In this case the message <strong>“I send the message”</strong> will become <strong>“I send$%message”</strong>. However there are some obstacles to overcome.</p>
<p>The first problem is that we need to know the language and somehow to define commonly used patterns in a dictionary. What would happen with a message written in some language we don’t know nothing about. Let’s say &#8211; Latin like the example bellow.</p>
<blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras venenatis, sapien eget suscipit placerat, justo quam blandit mauris, quis tempor ante sapien sodales augue. Praesent ut mauris quam. Phasellus scelerisque, ante quis consequat tristique, metus turpis consectetur leo, vitae facilisis sapien mi eu sapien. Praesent vitae ligula elit, et faucibus augue. Sed rhoncus sodales dolor ut gravida. In quis augue ac nulla auctor mattis sed sed libero. Donec eget purus eget enim tempor porta vitae eget diam. Mauris aliquet malesuada ipsum, non pulvinar urna vestibulum ac. Donec feugiat velit vitae nunc cursus imperdiet. Donec accumsan faucibus dictum. Phasellus sed mauris sapien. Maecenas mi metus, tincidunt sed rhoncus nec, sodales non sapien.</p></blockquote>
<p>Clearly without knowing Latin it isn’t easy to define which are those commonly used patterns. The thing is that it&#8217;s better to use pattern substitution if you know in advance the set of words and characters.</p>
<p>The second problem is related to decompression. It is obvious that we need to define a dictionary and this dictionary must be used when decoding the message. It will be great also if we find more patterns longer than three characters. If not, the compression ratio will be low. Unfortunately such patterns aren’t very common in any natural language.</p>
<figure id="attachment_2643" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/PatternSubstitutiononTexts.png"><img src="/wp-content/uploads/2012/01/PatternSubstitutiononTexts.png" alt="Text compression with diagram encoding and pattern substitution" title="Text compression with diagram encoding and pattern substitution" width="620" class="size-full wp-image-2643" srcset="/wp-content/uploads/2012/01/PatternSubstitutiononTexts.png 683w, /wp-content/uploads/2012/01/PatternSubstitutiononTexts-300x128.png 300w" sizes="(max-width: 683px) 100vw, 683px" /></a><figcaption class="wp-caption-text">Diagram encoding and pattern substitution are far more suitable for text compression than run-length encoding. In fact, pattern substitution is very effective on compressing programming languages.</figcaption></figure>
<h2>Application</h2>
<p>It is interesting to answer the question, how to use diagram encoding or patter substitution to compress text in natural language, especially when we don’t know the language in detail? The answer hides in the question. We wont compress natural languages, but machine language. Exactly machine (programming) languages are limited to a smaller sets of words and symbols. Isn’t it true for any programing language? Like PHP, where words like <strong>“function”</strong>, <strong>“while”</strong>, <strong>“for”</strong>, <strong>“break”</strong>, <strong>“switch”</strong>, <strong>“foreach”</strong> happen to be often in use, or HTML with its defined set of tags. Perhaps the best example is CSS, where only the values of the properties can vary. CSS files also tend to have multiple new lines, tabs and spaces, which only humans read.</p>
<p>The question here is why should we compress those file types. It’s clear that after the compression they will be completely useless, both for humans and machines. Yes, that is true, but what if we have to store versions of those files into a DB. Kind of a backup. Imagine you’re working for a web hosting company that has to store daily versions of the sites it’s hosting. Thus the volume of stored information even for small companies hosting only few sites can be enormous. The problem is that compressing those files with some conventional compressing tool isn’t a good idea. Thus we’ve to save a copy of the entire site every day, but as we know the difference between daily versions of a site can be small. A version control system is another solution, but then you’ve to store the plain text of the files. </p>
<p>Perhaps a better approach is to compress the text using pattern substitution and then saving only differences &#8211; kind of version control, which can be done with “relative encoding”.</p>
<p>Using the above method we can save lots of disk space and in the same time we can compress/decompress easily. Another good thing is that you can save only changes to the initial files, like version control, which can also be compressed.</p>
<h2>Implementation</h2>
<p>The implementation of this algorithm is again on PHP and tries only to describe the main principles of compression. In this case I tried to compress a CSS file using the compression above. Although this example is quite primitive we can see some interesting facts. First of all you only need encoding and decoding dictionaries. Practically the encoding and decoding processes are equal, so you don’t need to implement two different functions. Here in this example a native PHP function is used &#8211; str_replace, because the purpose of this algorithm is not to describe pattern substitution techniques, but pattern substitution. It assumes that today’s programming languages have string manipulation functions for the purposes of this task.</p>
<pre lang="PHP">
$str = file_get_contents('large_style_file.css');

$encoding_dict = array(
	"\n" 		=> '$0',
	'text' 		=> '$1',
	'color' 	=> '$2',
	'display' 	=> '$3',
	'font' 		=> '$4',
	'width' 	=> '$5',
	'height'	=> '$6',	
	' '		=> '',
);

function replace_patterns($input, $dict) 
{
	foreach ($dict as $pattern => $replace) {
		$input = str_replace($pattern, $replace, $input);
	}
	
	return $input;
}

$result = replace_patterns($str, $encoding_dict);
</pre>
<p>By only replacing few CSS properties I achieved almost 40% of compression ratio (as shows the diagram bellow). The initial file is 202 KB, while compressed it&#8217;s only 131 KB. Of course, it all depends on the CSS file, but how about replacing all property names with shorter ones. Perhaps then the compression will be even better.</p>
<figure id="attachment_2647" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/chart_1.png"><img src="/wp-content/uploads/2012/01/chart_1.png" alt="CSS compression with pattern substitution" title="CSS compression with pattern substitution" width="600" height="371" class="size-full wp-image-2647" srcset="/wp-content/uploads/2012/01/chart_1.png 600w, /wp-content/uploads/2012/01/chart_1-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/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/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/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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
