<?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>algorithms &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/algorithms/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>Data Structures Infographic: Linked List</title>
		<link>/2017/09/10/data-structures-infographic-linked-list/</link>
		<comments>/2017/09/10/data-structures-infographic-linked-list/#respond</comments>
		<pubDate>Sun, 10 Sep 2017 08:51:13 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[infographic]]></category>
		<category><![CDATA[Linked list]]></category>

		<guid isPermaLink="false">/?p=3642</guid>
		<description><![CDATA[Find it on GitHub<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2018/02/11/data-structures-infographic-tree/" rel="bookmark" title="Data Structures Infographic: Tree">Data Structures Infographic: Tree </a></li>
<li><a href="/2017/09/14/data-structures-infographic-stack-queue/" rel="bookmark" title="Data Structures Infographic: Stack &#038; Queue">Data Structures Infographic: Stack &#038; Queue </a></li>
<li><a href="/2017/09/02/data-structures-infographic-arrays/" rel="bookmark" title="Data Structures Infographic: Arrays">Data Structures Infographic: Arrays </a></li>
<li><a href="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" rel="bookmark" title="Computer Algorithms: Detecting and Breaking a Loop in a Linked List">Computer Algorithms: Detecting and Breaking a Loop in a Linked List </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><a href="/wp-content/uploads/2017/09/Linked_List.png"><img class="alignnone size-full wp-image-3643" src="https://raw.githubusercontent.com/stoimen/infographics/master/Linked_List.png" alt="" width="800" height="1200" /></a></p>
<p>Find it on <a href="https://github.com/stoimen/infographics/blob/master/Linked_List.png">GitHub</a></p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2018/02/11/data-structures-infographic-tree/" rel="bookmark" title="Data Structures Infographic: Tree">Data Structures Infographic: Tree </a></li>
<li><a href="/2017/09/14/data-structures-infographic-stack-queue/" rel="bookmark" title="Data Structures Infographic: Stack &#038; Queue">Data Structures Infographic: Stack &#038; Queue </a></li>
<li><a href="/2017/09/02/data-structures-infographic-arrays/" rel="bookmark" title="Data Structures Infographic: Arrays">Data Structures Infographic: Arrays </a></li>
<li><a href="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" rel="bookmark" title="Computer Algorithms: Detecting and Breaking a Loop in a Linked List">Computer Algorithms: Detecting and Breaking a Loop in a Linked List </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2017/09/10/data-structures-infographic-linked-list/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Multiplication</title>
		<link>/2013/01/14/computer-algorithms-multiplication/</link>
		<comments>/2013/01/14/computer-algorithms-multiplication/#comments</comments>
		<pubDate>Mon, 14 Jan 2013 14:40:54 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Addition]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[computer algorithms]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Multiplication]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">/?p=3531</guid>
		<description><![CDATA[Introduction Perhaps right after the addition at school we’ve learned how to multiply two numbers. This algorithm isn’t as easy as addition, but besides that we’re so familiar with it and that we even don’t recognize it as an “algorithm”. We just know it by heart. However, as I already said, multiplication is a bit &#8230; <a href="/2013/01/14/computer-algorithms-multiplication/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Multiplication</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/11/26/computer-algorithms-strassens-matrix-multiplication/" rel="bookmark" title="Computer Algorithms: Strassen&#8217;s Matrix Multiplication">Computer Algorithms: Strassen&#8217;s Matrix Multiplication </a></li>
<li><a href="/2012/05/15/computer-algorithms-karatsuba-fast-multiplication/" rel="bookmark" title="Computer Algorithms: Karatsuba Fast Multiplication">Computer Algorithms: Karatsuba Fast Multiplication </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2013/01/07/computer-algorithms-adding-large-integers/" rel="bookmark" title="Computer Algorithms: Adding Large Integers">Computer Algorithms: Adding Large Integers </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Perhaps right after the <a title="Computer Algorithms: Adding Large Integers" href="/2013/01/07/computer-algorithms-adding-large-integers/">addition </a>at school we’ve learned how to multiply two numbers. This algorithm isn’t as easy as addition, but besides that we’re so familiar with it and that we even don’t recognize it as an “algorithm”. We just know it by heart.</p>
<p>However, as I already said, multiplication is a bit more difficult than addition. This algorithm is interesting because for several reasons. First of all, let’s compare multiplication in binary and decimal.</p>
<p>So, let’s see how to multiply two numbers.</p>
<h2>Overview</h2>
<p>Multiplying and adding is practically the same thing, so where’s the difference?</p>
<p>It’s clear that a product of two numbers (each with N digits) can be represented as N sums, as we can see on the next picture.</p>
<figure id="attachment_3540" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2013/01/1.-Multiplication-Addition.png"><img class="size-full wp-image-3540" alt="Multiplication &amp; Addition" src="/wp-content/uploads/2013/01/1.-Multiplication-Addition.png" width="620" height="399" srcset="/wp-content/uploads/2013/01/1.-Multiplication-Addition.png 620w, /wp-content/uploads/2013/01/1.-Multiplication-Addition-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Now, for larger integers each time we shift left the next intermediate sum.</p>
<p><figure id="attachment_3539" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2013/01/2.-Multiplication.png"><img class="size-full wp-image-3539" alt="Multiplication" src="/wp-content/uploads/2013/01/2.-Multiplication.png" width="620" height="399" srcset="/wp-content/uploads/2013/01/2.-Multiplication.png 620w, /wp-content/uploads/2013/01/2.-Multiplication-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure><span id="more-3531"></span></p>
<p>That is absolutely logical since we can represent the numbers as a sum of decimals divisible by 10 without a remainder.</p>
<figure id="attachment_3538" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2013/01/3.-Multiplication-Part-2.png"><img class="size-full wp-image-3538" alt="Multiplication " src="/wp-content/uploads/2013/01/3.-Multiplication-Part-2.png" width="620" height="399" srcset="/wp-content/uploads/2013/01/3.-Multiplication-Part-2.png 620w, /wp-content/uploads/2013/01/3.-Multiplication-Part-2-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<h2>Binary Multiplication</h2>
<p>Sometimes binary is easier to work with than decimal and multiplication is just the case. As shown on the picture below binary multiplication is much easier compared to decimal.</p>
<figure id="attachment_3537" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2013/01/4.-Binary-Multiplication.png"><img class="size-full wp-image-3537" alt="Binary " src="/wp-content/uploads/2013/01/4.-Binary-Multiplication.png" width="620" height="399" srcset="/wp-content/uploads/2013/01/4.-Binary-Multiplication.png 620w, /wp-content/uploads/2013/01/4.-Binary-Multiplication-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>That’s because we multiply only by 1 and 0, so the intermediate sum can be either the first number or 0.</p>
<p>In the oder hand, shifting left in binary equals multiplication by 2.</p>
<figure id="attachment_3536" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2013/01/5.-Binary-Shift-Left.png"><img class="size-full wp-image-3536" alt="Binary " src="/wp-content/uploads/2013/01/5.-Binary-Shift-Left.png" width="620" height="399" srcset="/wp-content/uploads/2013/01/5.-Binary-Shift-Left.png 620w, /wp-content/uploads/2013/01/5.-Binary-Shift-Left-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Why? Well, simply because the base is 2. It’s practically the same with decimals where shifting left equals multiplying by 10.</p>
<figure id="attachment_3535" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2013/01/6.-Decimal-Shift-Left.png"><img class="size-full wp-image-3535" alt="Decimal " src="/wp-content/uploads/2013/01/6.-Decimal-Shift-Left.png" width="620" height="399" srcset="/wp-content/uploads/2013/01/6.-Decimal-Shift-Left.png 620w, /wp-content/uploads/2013/01/6.-Decimal-Shift-Left-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>The same applies of course for any base, i.e. hex F equals decimal 15 (since the first number is 0) and FF equals 255 (which is 16&#215;16 &#8211; 1).</p>
<h2>Can we do better?</h2>
<p>Unlike <a title="Computer Algorithms: Adding Large Integers" href="/2013/01/07/computer-algorithms-adding-large-integers/">addition</a>, here the answer is &#8211; yes, and we already know how to multiply faster (either decimal or binary numbers) using the <a title="Computer Algorithms: Karatsuba Fast Multiplication" href="/2012/05/15/computer-algorithms-karatsuba-fast-multiplication/">Karatsuba’s fast multiplication algorithm</a>.</p>
<h1>It’s Important Because …</h1>
<p>I&#8217;ve to admit that both addition and multiplication algorithms are fairly to understand, but we must remember that they are giving us the ground level for more complex cryptographic algorithms.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/11/26/computer-algorithms-strassens-matrix-multiplication/" rel="bookmark" title="Computer Algorithms: Strassen&#8217;s Matrix Multiplication">Computer Algorithms: Strassen&#8217;s Matrix Multiplication </a></li>
<li><a href="/2012/05/15/computer-algorithms-karatsuba-fast-multiplication/" rel="bookmark" title="Computer Algorithms: Karatsuba Fast Multiplication">Computer Algorithms: Karatsuba Fast Multiplication </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2013/01/07/computer-algorithms-adding-large-integers/" rel="bookmark" title="Computer Algorithms: Adding Large Integers">Computer Algorithms: Adding Large Integers </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2013/01/14/computer-algorithms-multiplication/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Detecting and Breaking a Loop in a Linked List</title>
		<link>/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/</link>
		<comments>/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/#comments</comments>
		<pubDate>Tue, 17 Jul 2012 07:43:05 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[$_head]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Hare]]></category>
		<category><![CDATA[HEAD]]></category>
		<category><![CDATA[Infinite loop]]></category>
		<category><![CDATA[Linked]]></category>
		<category><![CDATA[Linked list]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pointer]]></category>

		<guid isPermaLink="false">/?p=3243</guid>
		<description><![CDATA[Introduction Linked lists are one very common and handy data structure that can be used in many cases of the practical programming. In this post we&#8217;ll assume that we&#8217;re talking about singly linked list. This means that each item is pointed by it&#8217;s previous item and it points to it&#8217;s next item. In this scenario &#8230; <a href="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Detecting and Breaking a Loop in a Linked List</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" rel="bookmark" title="Computer Algorithms: Linked List">Computer Algorithms: Linked List </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2012/06/05/computer-algorithms-stack-and-queue-data-structure/" rel="bookmark" title="Computer Algorithms: Stack and Queue">Computer Algorithms: Stack and Queue </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Linked lists are one very common and handy data structure that can be used in many cases of the practical programming. In this post we&#8217;ll assume that we&#8217;re talking about singly linked list. This means that each item is pointed by it&#8217;s previous item and it points to it&#8217;s next item. In this scenario the first item of the list, its head, doesn&#8217;t have an ancestor and the last item doesn&#8217;t have a successor.</p>
<figure id="attachment_3260" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/1.-Singly-Linked-List.png"><img class="size-full wp-image-3260" title="Singly Linked List" src="/wp-content/uploads/2012/07/1.-Singly-Linked-List.png" alt="Singly Linked List" width="619" height="158" srcset="/wp-content/uploads/2012/07/1.-Singly-Linked-List.png 619w, /wp-content/uploads/2012/07/1.-Singly-Linked-List-300x76.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Sometimes, due to bugs or bad architecture or complexity of the applications we can have problems with lists. One very typical problem is having a loop, which in breve means that some of the items of the list is pointed twice, as shown on the image below.</p>
<figure id="attachment_3262" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/2.-Loop-in-a-Singly-Linked-List.png"><img src="/wp-content/uploads/2012/07/2.-Loop-in-a-Singly-Linked-List.png" alt="Loop in a Singly Linked List" title="Loop in a Singly Linked List" width="618" height="247" class="size-full wp-image-3262" srcset="/wp-content/uploads/2012/07/2.-Loop-in-a-Singly-Linked-List.png 618w, /wp-content/uploads/2012/07/2.-Loop-in-a-Singly-Linked-List-300x119.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>So in first place we need to be sure that there is a loop and then: how can we break it!</p>
<p>There are several algorithms on finding a loop, but here’s one very basic. It’s known as the <a href="http://en.wikipedia.org/wiki/Robert_Floyd" title="Robert W. Floyd">Floyd</a>’s algorithm or the algorithm of the tortoise and hare.<span id="more-3243"></span></p>
<h2>Overview</h2>
<p>The Floyd’s algorithm relies on one very simple idea. Initially we set two pointers to the head of the list. </p>
<figure id="attachment_3265" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/3.-Tortoise-and-Hare.png"><img src="/wp-content/uploads/2012/07/3.-Tortoise-and-Hare.png" alt="Tortoise and Hare" title="Tortoise and Hare" width="620" height="399" class="size-full wp-image-3265" srcset="/wp-content/uploads/2012/07/3.-Tortoise-and-Hare.png 620w, /wp-content/uploads/2012/07/3.-Tortoise-and-Hare-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>On each step we increment both pointers, but the hare is incremented by two elements, while the tortoise walks on every single item &#8211; as shown on the images bellow.</p>
<figure id="attachment_3266" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/4.-Hare.png"><img src="/wp-content/uploads/2012/07/4.-Hare.png" alt="Hare" title="Hare" width="620" height="399" class="size-full wp-image-3266" srcset="/wp-content/uploads/2012/07/4.-Hare.png 620w, /wp-content/uploads/2012/07/4.-Hare-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The hare is fast and jumps by a pair of items at once!</figcaption></figure>
<p>The tortoise, as it&#8217;s clear from the image bellow, is much slower.</p>
<figure id="attachment_3267" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/5.-Tortoise.png"><img src="/wp-content/uploads/2012/07/5.-Tortoise.png" alt="Tortoise" title="Tortoise" width="620" height="399" class="size-full wp-image-3267" srcset="/wp-content/uploads/2012/07/5.-Tortoise.png 620w, /wp-content/uploads/2012/07/5.-Tortoise-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The tortoise is much slower than the hare!</figcaption></figure>
<p>As a result if we don’t have a loop in the list the hare will hit the end of the list, but if we do have a loop the hare will catch-up the tortoise inside the loop.</p>
<figure id="attachment_3268" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/6.-Movements.png"><img src="/wp-content/uploads/2012/07/6.-Movements.png" alt="Movements" title="Movements" width="620" height="399" class="size-full wp-image-3268" srcset="/wp-content/uploads/2012/07/6.-Movements.png 620w, /wp-content/uploads/2012/07/6.-Movements-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Since the hare is faster and both the hare and the tortoise are in the loop &#8211; the faster pointer will catch-up the tortoise!</figcaption></figure>
<h2>Code</h2>
<p>Assuming a typical representation of a singly linked list here’s a sample code in PHP.</p>
<h3>The Item Class</h3>
<pre lang="PHP">
class Item
{
    protected $_name = '';
    protected $_key = '';
    protected $_next = null;
    
    public function __construct($key, $name)
    {
        $this->_key = $key;
        $this->_name = $name;
    }
    
    public function setNext(&$next) { $this->_next = $next; }
    public function &getNext() { return $this->_next; }
    
    public function setKey($key) { $this->_key = $key; }
    public function getKey() { return $this->_key; }
    
    public function setName($name) { $this->_name = $name; }
    public function getName() { return $this->_name; }
    
    public function __toString()
    {
        return $this->_key . ' ' . $this->_name . "\n";
    }
}
</pre>
<h3>The List Class</h3>
<pre lang="PHP">
class Linked_List 
{
    protected $_head = null;
    
    public function insert($item)
    {
        if ($this->_head == null) {
            $this->_head = $item;
            return;
        }
        
        $current = $this->_head;
        while ($current->getNext()) {
            $current = $current->getNext();
        }
        
        $current->setNext($item);
    }
    
    public function detectLoop()
    {
        $tortoise = $hare = $this->_head;
        
        if ($hare->getNext() != null) {
            $hare = $hare->getNext()->getNext();
        } else {
            return FALSE;
        }
        
        while ($hare) {
            if ($hare == $tortoise) {
                return $hare;
            }
            
            if ($hare->getNext()) {
                $hare = $hare->getNext()->getNext();
            } else {
                return FALSE;
            }
            
            $tortoise = $tortoise->getNext();
        }
        
        return FALSE;
    }
    
    protected function _isReachable($a, $b) 
    {
        $current = $b;
        while ($current->getNext() != $b) {
            if ($current->getNext() == $a) {
                return $current;
            }
            $current = $current->getNext();
        }
        
        return FALSE;
    }
    
    public function breakLoop()
    {
        if (FALSE === ($loop = $this->detectLoop())) {
            return;
        }
        
        $startOfTheLoop = $this->_head;
        
        while (FALSE === ($lastLoopItem = $this->_isReachable($startOfTheLoop, $loop))) {
            $startOfTheLoop = $startOfTheLoop->getNext();
        }
        
        $pseudoNext = null;
        $lastLoopItem->setNext($pseudoNext);
    }
    
    public function __toString()
    {
        $current = $this->_head;
        $output = '';
        
        while ($current) {
            $output .= $current->getKey() . ' ' . $current->getName() . "\n";
            $current = $current->getNext();
        }
        
        return $output;
    }
}
</pre>
<h3>Initialization</p>
<h3>
<pre lang="PHP">
$items = array();
$ll = new Linked_List();

for ($i = 0; $i < 100; $i++) {
    $items[$i] = new Item($i, 'Item #' . $i);
    $ll->insert($items[$i]);
}

// 0 Item #0
// 1 Item #1
// ...
// 99 Item #99
echo $ll;
</pre>
<h2>Breaking the Loop</h2>
<p>In order to break the loop we need first to check whether an item is reachable from within the loop. Once we know that we should return the last loop item in order to improve the performance of the next method &#8211; breakLoop. This is made with the following method:</p>
<pre lang="PHP">
    protected function _isReachable($a, $b) 
    {
        $current = $b;
        while ($current->getNext() != $b) {
            if ($current->getNext() == $a) {
                return $current;
            }
            $current = $current->getNext();
        }
        
        return FALSE;
    }
</pre>
<p>Now we can break the loop by removing the double link to the first item of the loop. </p>
<pre lang="PHP">
    // member of Linked_List
    public function breakLoop()
    {
        if (FALSE === ($loop = $this->detectLoop())) {
            return;
        }
        
        $startOfTheLoop = $this->_head;
        
        while (FALSE === ($lastLoopItem = $this->_isReachable($startOfTheLoop, $loop))) {
            $startOfTheLoop = $startOfTheLoop->getNext();
        }
        
        $pseudoNext = null;
        $lastLoopItem->setNext($pseudoNext);
    }
</pre>
<h2>Complexity</h2>
<p>Assuming that the list length is N and the loop length is M, we&#8217;ll break the loop in O((N-M)*M) time complexity only after we&#8217;ve found the loop. The question is how fast we can find the loop with the algorithm above? Well the hare is pretty fast and can pass through some of the items of the loop several times, but the tortoise walks sequentially over all the items. The question is will the hare catch-up the tortoise before the last one gets to the end of the loop? The answer is yes and we can think of a single linked list without loops where there are two pointers starting from the beginning of the list. The same question can be translated to: will the faster pointer reach the end before the slower one gets to the middle of the list &#8211; well yes.</p>
<p>Finally the answer is O(N) for answering whether there&#8217;s a loop and O(M*(N-M)) to break it.</p>
<p>However the good news is that when we work with linked lists we often work only with pointers (which is our case in this post) and thus we don&#8217;t need additional memory which makes them very useful. Actually we will see the same advantage in the next algorithm &#8211; reversing a linked list, which is more effective than reversing an array.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" rel="bookmark" title="Computer Algorithms: Linked List">Computer Algorithms: Linked List </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2012/06/05/computer-algorithms-stack-and-queue-data-structure/" rel="bookmark" title="Computer Algorithms: Stack and Queue">Computer Algorithms: Stack and Queue </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: How to Determine the Day of the Week</title>
		<link>/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/</link>
		<comments>/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/#comments</comments>
		<pubDate>Tue, 24 Apr 2012 19:31:03 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Calculating the day of the week]]></category>
		<category><![CDATA[Calendars]]></category>
		<category><![CDATA[Chronology]]></category>
		<category><![CDATA[computer]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Doomsday rule]]></category>
		<category><![CDATA[February]]></category>
		<category><![CDATA[Gregorian calendar]]></category>
		<category><![CDATA[informatics]]></category>
		<category><![CDATA[Julian calendar]]></category>
		<category><![CDATA[Leap year]]></category>
		<category><![CDATA[month]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Units of time]]></category>
		<category><![CDATA[USD]]></category>
		<category><![CDATA[Year zero]]></category>

		<guid isPermaLink="false">/?p=3058</guid>
		<description><![CDATA[Introduction Do you know what day of the week was the day you were born? Monday or maybe Saturday? Well, perhaps you know that. Everybody know the day he’s born on, but do you know what day was the 31st January 1883? No? Well, there must be some method to determine any day in any &#8230; <a href="/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: How to Determine the Day of the Week</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/" rel="bookmark" title="Computer Algorithms: Determine if a Number is Prime">Computer Algorithms: Determine if a Number is Prime </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
<li><a href="/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="/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/" rel="bookmark" title="How to Check if a Date is More or Less Than a Month Ago with PHP">How to Check if a Date is More or Less Than a Month Ago with PHP </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Do you know what day of the week was the day you were born? Monday or maybe Saturday? Well, perhaps you know that. Everybody know the day he’s born on, but do you know what day was the 31st January 1883? No? Well, there must be some method to determine any day in any century.</p>
<p>We know that 2012 started at Sunday. After we know that it’s easy to determine what day is the 2nd of January. It should be Monday. But things get a little more complex if we try to guess some date distant from January the 1st. Indeed 1st of Jan was on Sunday, but what day is 9th of May the same year. This is far more difficult to say. Of course we can go with a brute force approach and count from 1/Jan till 9/May, but that is quite slow and error prone.</p>
<figure id="attachment_3079" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/FollowingDays.png"><img class="size-full wp-image-3079" title="Following Days" src="/wp-content/uploads/2012/04/FollowingDays.png" alt="Following Days" width="619" height="315" srcset="/wp-content/uploads/2012/04/FollowingDays.png 619w, /wp-content/uploads/2012/04/FollowingDays-300x152.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">If 1st of January is Sunday the most logical thing to happen is 2nd of January to be Monday</figcaption></figure>
<p>So what we’ll do if we have to code a program that answers this question. The most easier way is to use a library. Almost every major library has built-in functions that can answer what day is on a given date. Such are date() in PHP or getDate() in JavaScript. But the question remains. How these library functions know the answer and how can we code such library function if our library doesn’t support such functionality?</p>
<p>There must be some algorithm to help us.<span id="more-3058"></span></p>
<h2>Overview</h2>
<p>Because months has different number of days, and most of them aren’t divisible by 7 without a remainder, months begin on different days. Thus if January begins on Sunday, the month of February the same year will begin on Wednesday. Of course in common years February has 28 days, which fortunately is divisible by 7 and thus February and March both begin on the same day, which is great, but isn’t true for leap years.</p>
<h3>What Do We Know About the Calendar</h3>
<p>First thing to know is that each week has exactly 7 days. We know also that a common year has 365 days, while a leap year has one day more &#8211; 366. Most of the months has 30 or 31 days, but February has only 28 days in common years and 29 in leap years.</p>
<p>Because 365 mod 7 = 1 in a common year each year begins exactly on the next day of the preceding year. Thus if 2011 started on Saturday, 2012 starts on Sunday. And yet again that is because 2011 is not a leap year.</p>
<figure id="attachment_3081" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/SomeStatistics.png"><img class="size-full wp-image-3081" title="Some Statistics" src="/wp-content/uploads/2012/04/SomeStatistics.png" alt="Some Statistics" width="620" height="254" srcset="/wp-content/uploads/2012/04/SomeStatistics.png 620w, /wp-content/uploads/2012/04/SomeStatistics-300x122.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">A week always has 7 days, while a year has different number of days depending on the fact whether it&#39;s a leap or not!</figcaption></figure>
<p>What else do we know? Because a week has exactly seven days only February (with its 28 days in a common year) is divisible by 7 (28 mod 7 = 0) and has exactly four weeks in it. Thus in a common year February and March start on a same day. Unfortunately that is not true about the other months.</p>
<p>All these things we know about the calendar are great, so we can make some conclusions. Although eleven of the months have either 30 or 31 days they don’t start on a same day, but some of the months do appear to start on a same day just because the number of days between them is divisible by 7 without a remainder.</p>
<p>Let’s take a look on some examples. For instance September has 30 days, as November, while October, which is in between them has 31 days. Thus 30+30+31 makes 91. Fortunately 91 mod 7 = 0. So for each year September and December start on the same day (as they are after February they don’t depend on leap years). The same thing occurs to April and July and the good news is that in leap years even January starts on the same day as April and July.</p>
<figure id="attachment_3082" style="width: 623px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7.png"><img class="size-full wp-image-3082" title="Periods of Days Divisible by 7" src="/wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7.png" alt="Periods of Days Divisible by 7" width="623" height="508" srcset="/wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7.png 623w, /wp-content/uploads/2012/04/PeriodsofDaysDivisibleby7-300x244.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></a><figcaption class="wp-caption-text">Not only the number of days in February is divisible by 7. The sum of days of April, May and June is also divisible by 7!</figcaption></figure>
<p>Now we know that there are some relations between months. Thus if we know somehow that 13th of April is Monday, we’ll be sure that 13th of July is also Monday. Let’s see now a summary of these observations.</p>
<figure id="attachment_3083" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear.png"><img class="size-full wp-image-3083" title="Corresponding Months in a Common Year" src="/wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear.png" alt="Corresponding Months in a Common Year" width="621" height="516" srcset="/wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear.png 621w, /wp-content/uploads/2012/04/CorrespondingMonthsinaCommonYear-300x249.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">In a common year some months correspond!</figcaption></figure>
<p>We can also refer the following diagram.</p>
<figure id="attachment_3086" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear.png"><img class="size-full wp-image-3086" title="Table of Corresponding Months in a Common Year" src="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear.png" alt="Table of Corresponding Months in a Common Year" width="620" height="326" srcset="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear.png 620w, /wp-content/uploads/2012/04/TableofCorrespondingMonthsinaCommonYear-300x157.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">It&#39;s clearer to see the corresponding months in a table view!</figcaption></figure>
<p>For leap years there are other corresponding months. Let’s take a look at the following image.</p>
<figure id="attachment_3087" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear.png"><img class="size-full wp-image-3087" title="Corresponding Months in a Leap Year" src="/wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear.png" alt="Corresponding Months in a Leap Year" width="621" height="516" srcset="/wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear.png 621w, /wp-content/uploads/2012/04/CorrespondingMonthsinaLeapYear-300x249.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Corresponding months in a leap year differs from corresponding months in a common year!</figcaption></figure>
<p>Another way to get the same information is the following table.</p>
<figure id="attachment_3088" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear.png"><img class="size-full wp-image-3088" title="Table of Corresponding Months in a Leap Year" src="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear.png" alt="Table of Corresponding Months in a Leap Year" width="620" height="326" srcset="/wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear.png 620w, /wp-content/uploads/2012/04/TableofCorrespondingMonthsinaLeapYear-300x157.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Table view is easier to remember!</figcaption></figure>
<p>We know also that leap years happen to occur once per four years. However if there is a common year like the year 2001, which will be the next year that is common and starts and corresponds exactly on 2001? Because of leap years we can have a year starting on one of the seven days of the week and to be either leap or common. This means just 14 combinations.</p>
<p>Following these observations we can refer the following table.</p>
<pre lang="PHP">1700–1799     4
1800–1899     2
1900–1999     0
2000–2099     6
2100–2199     4
2200–2299     2
2300–2399     0
2400–2499     6
2500–2599     4
2600–2699     2</pre>
<p>You can clearly see the pattern “6 4 2 0”</p>
<p>Here’s the month table.</p>
<pre lang="PHP">Month		Common  	Leap
January 	0  		6
February	3 		2
March		3		3
April		6		6
May		1		1
June		4		4
July		6		6
August  	2		2
September	5		5
October 	0		0
November	3		3
December	5		5</pre>
<p>Columns 2 and 3 differs only for January and February.</p>
<p>Clearly the day table is as follows.</p>
<pre lang="PHP">Sunday  	0
Monday  	1
Tuesday 	2
Wednesday	3
Thursday	4
Friday  	5
Saturday	6</pre>
<p>Now let’s go back to the algorithm.</p>
<p>Using these tables and applying a simple formula we can calculate what day was on some given date. Here are the steps of this algorithm.</p>
<ol>
<li>Get the number for the corresponding century from the centuries table;</li>
<li>Get the last two digits from the year;</li>
<li>Divide the number from step 2 by 4 and get it without the remainder;</li>
<li>Get the month number from the month table;</li>
<li>Sum the numbers from steps 1 to 4;</li>
<li>Divide it by 7 and take the remainder;</li>
<li>Find the result of step 6 in the days table;</li>
</ol>
<h2>Implementation</h2>
<p>First let&#8217;s take a look on a simple practical example of the example above and then the code. Let’s answer the question from the first paragraph of this post.</p>
<p>What day was on January 31st, 1883?</p>
<ol>
<li>Take a look at the centuries table: for 1800 &#8211; 1899 this is 2.</li>
<li>Get the last two digits from the year: 83.</li>
<li>Divide 83 by 4 without a remainder: 83/4 = 20</li>
<li>Get the month number from the month table: Jan = 0.</li>
<li>Sum the numbers from steps 1 to 4: 2 + 83 + 20 + 0 = 105.</li>
<li>Divide it by 7 and take the remainder: 105 mod 7 = 0</li>
<li>Find the result of step 6 in the days table: Sunday = 0.</li>
</ol>
<p>The following code in PHP do implements the algorithm above.</p>
<pre lang="PHP">
function get_century_code($century)
{
	// XVIII
	if (1700 <= $century &#038;&#038; $century <= 1799)
		return 4;
		
	// XIX
	if (1800 <= $century &#038;&#038; $century <= 1899)
		return 2;
		
	// XX
	if (1900 <= $century &#038;&#038; $century <= 1999)
		return 0;
		
	// XXI
	if (2000 <= $century &#038;&#038; $century <= 2099)
		return 6;
		
	// XXII
	if (2100 <= $century &#038;&#038; $century <= 2199)
		return 4;
		
	// XXIII
	if (2200 <= $century &#038;&#038; $century <= 2299)
		return 2;
		
	// XXIV
	if (2300 <= $century &#038;&#038; $century <= 2399)
		return 0;
		
	// XXV
	if (2400 <= $century &#038;&#038; $century <= 2499)
		return 6;
	
	// XXVI
	if (2500 <= $century &#038;&#038; $century <= 2599)
		return 4;
	
	// XXVII
	if (2600 <= $century &#038;&#038; $century <= 2699)
		return 2;
}

/**
 * Get the day of a given date
 * 
 * @param $date
 */
function get_day_from_date($date) 
{
	$months = array(
		1 => 0,		// January
		2 => 3,		// February
		3 => 3,		// March
		4 => 6,		// April
		5 => 1,		// May
		6 => 4,		// June
		7 => 6,		// July
		8 => 2,		// August
		9 => 5,		// September
		10 => 0,	// October
		11 => 3,	// November
		12 => 5,	// December
	);
	
	$days = array(
		0 => 'Sunday',
		1 => 'Monday',
		2 => 'Tuesday',
		3 => 'Wednesday',
		4 => 'Thursday',
		5 => 'Friday',
		6 => 'Saturday',
	);
	
	// calculate the date
	$dateParts = explode('-', $date);
	$century = substr($dateParts[2], 0, 2);
	$year = substr($dateParts[2], 2);
	
	// 1. Get the number for the corresponding century from the centuries table
	$a = get_century_code($dateParts[2]);

	// 2. Get the last two digits from the year
	$b = $year;
	
	// 3. Divide the number from step 2 by 4 and get it without the remainder
	$c = floor($year / 4);
	
	// 4. Get the month number from the month table
	$d = $months[$dateParts[1]];

	// 5. Sum the numbers from steps 1 to 4
	$e = $a + $b + $c + $d;
	
	// 6. Divide it by 7 and take the remainder
	$f = $e % 7;
	
	// 7. Find the result of step 6 in the days table
	return $days[$f];
}

// Sunday
echo get_day_from_date('31-1-1883');
</pre>
<h2>Application</h2>
<p>This algorithm can be applied in many different cases although most of the libraries has built-in functions that can do that. The only problem besides that is that there are much more efficient algorithms that don&#8217;t need additional space (tables) of data. However this algorithm isn&#8217;t difficult to implement and it gives a good outlook of some facts in the calendar.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/" rel="bookmark" title="Computer Algorithms: Determine if a Number is Prime">Computer Algorithms: Determine if a Number is Prime </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
<li><a href="/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="/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/" rel="bookmark" title="How to Check if a Date is More or Less Than a Month Ago with PHP">How to Check if a Date is More or Less Than a Month Ago with PHP </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>You think you know &#8230; algorithms?</title>
		<link>/2012/04/11/you-think-you-know-algorithms/</link>
		<comments>/2012/04/11/you-think-you-know-algorithms/#respond</comments>
		<pubDate>Wed, 11 Apr 2012 08:04:34 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[quiz]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Super Quiz]]></category>
		<category><![CDATA[weekly quiz]]></category>

		<guid isPermaLink="false">/?p=3021</guid>
		<description><![CDATA[Note!– By reading this blog you can get the right answers! Loading&#8230; The answers will be published a week after the quiz has started!<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/02/29/you-think-you-know-javascript/" rel="bookmark" title="You think you know &#8230; javascript?">You think you know &#8230; javascript? </a></li>
<li><a href="/2012/03/09/you-think-you-know-php/" rel="bookmark" title="You think you know &#8230; PHP?">You think you know &#8230; PHP? </a></li>
<li><a href="/2012/03/07/you-think-you-know-javascript-quiz-results/" rel="bookmark" title="You think you know javascript. Quiz results!">You think you know javascript. Quiz results! </a></li>
<li><a href="/2012/05/09/you-think-you-know-algorithms-quiz-results-2/" rel="bookmark" title="You think you know algorithms. Quiz results!">You think you know algorithms. Quiz results! </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Note!– By reading this blog you can get the right answers!</p>
<p><iframe src="https://docs.google.com/spreadsheet/embeddedform?formkey=dHh3NkJiOTJYYkVNem9RVTNVWVh0V0E6MQ" width="640" height="1000" frameborder="0" marginheight="0" marginwidth="0">Loading&#8230;</iframe></p>
<p>The answers will be published a week after the quiz has started!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/02/29/you-think-you-know-javascript/" rel="bookmark" title="You think you know &#8230; javascript?">You think you know &#8230; javascript? </a></li>
<li><a href="/2012/03/09/you-think-you-know-php/" rel="bookmark" title="You think you know &#8230; PHP?">You think you know &#8230; PHP? </a></li>
<li><a href="/2012/03/07/you-think-you-know-javascript-quiz-results/" rel="bookmark" title="You think you know javascript. Quiz results!">You think you know javascript. Quiz results! </a></li>
<li><a href="/2012/05/09/you-think-you-know-algorithms-quiz-results-2/" rel="bookmark" title="You think you know algorithms. Quiz results!">You think you know algorithms. Quiz results! </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/11/you-think-you-know-algorithms/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Algorithms as Metro Stations</title>
		<link>/2012/03/28/algorithms-as-metro-stations/</link>
		<comments>/2012/03/28/algorithms-as-metro-stations/#comments</comments>
		<pubDate>Wed, 28 Mar 2012 10:05:28 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[algorithms on stoimen.com]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[metro stations]]></category>

		<guid isPermaLink="false">/?p=2976</guid>
		<description><![CDATA[If algorithms on stoimen.com were metro stations &#8211; here&#8217;s a map! Please click on the image for a larger image!<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/03/12/algorithm-cheatsheet-quicksort/" rel="bookmark" title="Algorithm cheatsheet: Quicksort">Algorithm cheatsheet: Quicksort </a></li>
<li><a href="/2012/05/09/you-think-you-know-algorithms-quiz-results-2/" rel="bookmark" title="You think you know algorithms. Quiz results!">You think you know algorithms. Quiz results! </a></li>
<li><a href="/2012/05/28/computer-algorithms-order-statistics-the-algorithm/" rel="bookmark" title="Computer Algorithms: Order Statistics">Computer Algorithms: Order Statistics </a></li>
<li><a href="/2012/02/13/computer-algorithms-insertion-sort/" rel="bookmark" title="Computer Algorithms: Insertion Sort">Computer Algorithms: Insertion Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>If algorithms on stoimen.com were metro stations &#8211; here&#8217;s a map!</p>
<figure id="attachment_2992" style="width: 613px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/AlgorithmsMetroStation.png"><img class="size-full wp-image-2992 " title="Algorithms as Metro Stations" src="/wp-content/uploads/2012/03/AlgorithmsMetroStationThumb.png" alt="Algorithms as Metro Stations" width="613" height="431" srcset="/wp-content/uploads/2012/03/AlgorithmsMetroStationThumb.png 613w, /wp-content/uploads/2012/03/AlgorithmsMetroStationThumb-300x210.png 300w" sizes="(max-width: 613px) 100vw, 613px" /></a><figcaption class="wp-caption-text">Next station - quicksort!</figcaption></figure>
<p>Please click on the image for a larger image!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/03/12/algorithm-cheatsheet-quicksort/" rel="bookmark" title="Algorithm cheatsheet: Quicksort">Algorithm cheatsheet: Quicksort </a></li>
<li><a href="/2012/05/09/you-think-you-know-algorithms-quiz-results-2/" rel="bookmark" title="You think you know algorithms. Quiz results!">You think you know algorithms. Quiz results! </a></li>
<li><a href="/2012/05/28/computer-algorithms-order-statistics-the-algorithm/" rel="bookmark" title="Computer Algorithms: Order Statistics">Computer Algorithms: Order Statistics </a></li>
<li><a href="/2012/02/13/computer-algorithms-insertion-sort/" rel="bookmark" title="Computer Algorithms: Insertion Sort">Computer Algorithms: Insertion Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/03/28/algorithms-as-metro-stations/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Algorithm cheatsheet: Quicksort</title>
		<link>/2012/03/12/algorithm-cheatsheet-quicksort/</link>
		<comments>/2012/03/12/algorithm-cheatsheet-quicksort/#comments</comments>
		<pubDate>Mon, 12 Mar 2012 14:49:37 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[cheatsheets]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[algorithm cheat sheet]]></category>
		<category><![CDATA[algorithm pseudo code]]></category>
		<category><![CDATA[Cheat sheet]]></category>
		<category><![CDATA[cheatsheet]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[pdf]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>

		<guid isPermaLink="false">/?p=2893</guid>
		<description><![CDATA[Click on the image to download this cheatsheet on PDF!<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/06/11/friday-algorithms-quicksort-difference-between-php-and-javascript/" rel="bookmark" title="Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript">Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2012/03/20/algorithm-cheatsheet-radix-sort/" rel="bookmark" title="Algorithm Cheatsheet: Radix Sort">Algorithm Cheatsheet: Radix Sort </a></li>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Click on the image to download this cheatsheet on PDF!</p>
<figure id="attachment_2901" style="width: 534px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/QuicksortCheatsheet.pdf"><img src="/wp-content/uploads/2012/03/QuicksortCheatsheet.png" alt="" title="Quicksort Cheatsheet" width="534" height="2000" class="size-full wp-image-2901" srcset="/wp-content/uploads/2012/03/QuicksortCheatsheet.png 534w, /wp-content/uploads/2012/03/QuicksortCheatsheet-80x300.png 80w" sizes="(max-width: 534px) 100vw, 534px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/06/11/friday-algorithms-quicksort-difference-between-php-and-javascript/" rel="bookmark" title="Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript">Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2012/03/20/algorithm-cheatsheet-radix-sort/" rel="bookmark" title="Algorithm Cheatsheet: Radix Sort">Algorithm Cheatsheet: Radix Sort </a></li>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/03/12/algorithm-cheatsheet-quicksort/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>You think you know algorithms. Quiz results!</title>
		<link>/2012/02/29/you-think-you-know-algorithms-quiz-results/</link>
		<comments>/2012/02/29/you-think-you-know-algorithms-quiz-results/#respond</comments>
		<pubDate>Wed, 29 Feb 2012 13:27:43 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[quiz]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[answers]]></category>
		<category><![CDATA[results]]></category>

		<guid isPermaLink="false">/?p=2790</guid>
		<description><![CDATA[1. Which is the fastest searching algorithm? Jump search Binary search correct answer Interpolation search 2. What is the complexity of binary search? O(log(n*n)) O(log(n)) correct answer O(n*log(n)) 3. Which search algorithm is faster? Binary search correct answer Fibonacci search 4. Which is better for natural language encoding? Run-length encoding Diagram encoding Pattern substitution correct &#8230; <a href="/2012/02/29/you-think-you-know-algorithms-quiz-results/" class="more-link">Continue reading <span class="screen-reader-text">You think you know algorithms. Quiz results!</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/05/09/you-think-you-know-algorithms-quiz-results-2/" rel="bookmark" title="You think you know algorithms. Quiz results!">You think you know algorithms. Quiz results! </a></li>
<li><a href="/2012/03/07/you-think-you-know-javascript-quiz-results/" rel="bookmark" title="You think you know javascript. Quiz results!">You think you know javascript. Quiz results! </a></li>
<li><a href="/2012/03/16/you-think-you-know-php-quiz-results/" rel="bookmark" title="You think you know PHP. Quiz Results!">You think you know PHP. Quiz Results! </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><strong>1. Which is the fastest searching algorithm?</strong></p>
<ul>
<li>Jump search</li>
<li>Binary search <span style="color: #339966;">correct answer</span></li>
<li>Interpolation search</li>
</ul>
<p><figure id="attachment_2824" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/answer2.png"><img class="size-full wp-image-2824" title="Which is the fastest searching algorithm?" src="/wp-content/uploads/2012/02/answer2.png" alt="Which is the fastest searching algorithm?" width="600" height="371" srcset="/wp-content/uploads/2012/02/answer2.png 600w, /wp-content/uploads/2012/02/answer2-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure><br />
<span id="more-2790"></span><br />
<strong>2. What is the complexity of binary search?</strong></p>
<ul>
<li>O(log(n*n))</li>
<li>O(log(n)) <span style="color: #339966;">correct answer</span></li>
<li>O(n*log(n))</li>
</ul>
<figure id="attachment_2822" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/answer1.png"><img src="/wp-content/uploads/2012/02/answer1.png" alt="What is the complexity of binary search?" title="AWhat is the complexity of binary search?" width="600" height="371" class="size-full wp-image-2822" srcset="/wp-content/uploads/2012/02/answer1.png 600w, /wp-content/uploads/2012/02/answer1-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p><strong>3. Which search algorithm is faster?</strong></p>
<ul>
<li>Binary search <span style="color: #339966;">correct answer</span></li>
<li>Fibonacci search</li>
</ul>
<figure id="attachment_2833" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/answer3.png"><img src="/wp-content/uploads/2012/02/answer3.png" alt="Which search algorithm is faster?" title="Which search algorithm is faster?" width="600" height="371" class="size-full wp-image-2833" srcset="/wp-content/uploads/2012/02/answer3.png 600w, /wp-content/uploads/2012/02/answer3-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p><strong>4. Which is better for natural language encoding?</strong></p>
<ul>
<li>Run-length encoding</li>
<li>Diagram encoding</li>
<li>Pattern substitution <span style="color: #339966;">correct answer</span></li>
</ul>
<figure id="attachment_2834" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/answer4.png"><img src="/wp-content/uploads/2012/02/answer4.png" alt="Which is better for natural language encoding?" title="Which is better for natural language encoding?" width="600" height="371" class="size-full wp-image-2834" srcset="/wp-content/uploads/2012/02/answer4.png 600w, /wp-content/uploads/2012/02/answer4-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p><strong>5. What is the complexity of searching into a hash table?</strong></p>
<ul>
<li>Quadratic</li>
<li>Logaritmic</li>
<li>Linear</li>
</ul>
<p><em>Note! &#8211; here (my fault) there&#8217;s no correct answer. The correct answer is that searching into a hash table has constant complexity &#8211; O(1). However I&#8217;ll assume that all of you that answered with &#8220;Linear&#8221; are right!</em></p>
<figure id="attachment_2835" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/answer5.png"><img src="/wp-content/uploads/2012/02/answer5.png" alt="What is the complexity of searching into a hash table?" title="What is the complexity of searching into a hash table?" width="600" height="371" class="size-full wp-image-2835" srcset="/wp-content/uploads/2012/02/answer5.png 600w, /wp-content/uploads/2012/02/answer5-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/05/09/you-think-you-know-algorithms-quiz-results-2/" rel="bookmark" title="You think you know algorithms. Quiz results!">You think you know algorithms. Quiz results! </a></li>
<li><a href="/2012/03/07/you-think-you-know-javascript-quiz-results/" rel="bookmark" title="You think you know javascript. Quiz results!">You think you know javascript. Quiz results! </a></li>
<li><a href="/2012/03/16/you-think-you-know-php-quiz-results/" rel="bookmark" title="You think you know PHP. Quiz Results!">You think you know PHP. Quiz Results! </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/02/29/you-think-you-know-algorithms-quiz-results/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Friday Algorithms: Input Data and Complexity</title>
		<link>/2010/09/03/friday-algorithms-input-data-and-complexity/</link>
		<comments>/2010/09/03/friday-algorithms-input-data-and-complexity/#comments</comments>
		<pubDate>Fri, 03 Sep 2010 09:32:47 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[algorithm complexity]]></category>
		<category><![CDATA[Computational complexity theory]]></category>
		<category><![CDATA[Context of computational complexity]]></category>
		<category><![CDATA[In-place algorithm]]></category>
		<category><![CDATA[input data]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Theoretical computer science]]></category>

		<guid isPermaLink="false">/?p=1955</guid>
		<description><![CDATA[Size of .. As we all know most of the cases a program execution time depends most from the input data. As I wrote in my post the degree of the input data estimates the algorithm complexity. Of course 3*n² is a bit faster than 5*n², but in general both functions are similar and have &#8230; <a href="/2010/09/03/friday-algorithms-input-data-and-complexity/" class="more-link">Continue reading <span class="screen-reader-text">Friday Algorithms: Input Data and Complexity</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/" rel="bookmark" title="Friday Algorithms: A Data Structure: JavaScript Stack">Friday Algorithms: A Data Structure: JavaScript Stack </a></li>
<li><a href="/2012/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/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Size of ..</h2>
<p>As we all know most of the cases a program execution time depends most from the input data. As I wrote in my <a title="Algorithm complexity and estimation" href="/2010/08/29/beginning-algorithm-complexity-and-estimation/" target="_blank">post</a> the degree of the input data estimates the algorithm complexity.</p>
<p>Of course 3*n² is a bit faster than 5*n², but in general both functions are similar and have the same complexity. In this case we tend to say that the size of the input data is n.</p>
<figure id="attachment_1961" style="width: 430px" class="wp-caption alignnone"><a href="/wp-content/uploads/2010/09/input-data.jpg"><img class="size-full wp-image-1961 " title="input-data" src="/wp-content/uploads/2010/09/input-data.jpg" alt="Size of the input data" width="430" height="137" srcset="/wp-content/uploads/2010/09/input-data.jpg 430w, /wp-content/uploads/2010/09/input-data-300x95.jpg 300w" sizes="(max-width: 430px) 100vw, 430px" /></a><figcaption class="wp-caption-text">The size of the input data affects the complexity of the algorithm</figcaption></figure>
<p>It is easy to bind this to arrays or other simple data structures. For example when sorting an array with n elements, the size of the input data is n, but sometimes there is not such an obvious relation between an algorithm and the size of the input data.</p>
<p>For instance when we&#8217;ve to search a path into a graph, than maybe the best way to describe the input data is by summing both the number of vertices and the number of edges.</p>
<h2>Conclusion</h2>
<figure id="attachment_1963" style="width: 430px" class="wp-caption alignnone"><a href="/wp-content/uploads/2010/09/think.jpg"><img class="size-full wp-image-1963 " title="Think, think, think" src="/wp-content/uploads/2010/09/think.jpg" alt="Think, think, think" width="430" height="286" srcset="/wp-content/uploads/2010/09/think.jpg 430w, /wp-content/uploads/2010/09/think-300x199.jpg 300w" sizes="(max-width: 430px) 100vw, 430px" /></a><figcaption class="wp-caption-text">Think, think, think</figcaption></figure>
<p>However this is important when dealing with algorithms, because a mistake in the estimation of the input data size will result in wrong algorithm estimation at all</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/07/16/friday-algorithms-a-data-structure-javascript-stack/" rel="bookmark" title="Friday Algorithms: A Data Structure: JavaScript Stack">Friday Algorithms: A Data Structure: JavaScript Stack </a></li>
<li><a href="/2012/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/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/09/03/friday-algorithms-input-data-and-complexity/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Beginning Algorithm Complexity and Estimation</title>
		<link>/2010/08/29/beginning-algorithm-complexity-and-estimation/</link>
		<comments>/2010/08/29/beginning-algorithm-complexity-and-estimation/#respond</comments>
		<pubDate>Sun, 29 Aug 2010 11:05:47 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Analysis of algorithms]]></category>
		<category><![CDATA[Asymptotic analysis]]></category>
		<category><![CDATA[Big O notation]]></category>
		<category><![CDATA[C syntax]]></category>
		<category><![CDATA[complexity]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[IP]]></category>
		<category><![CDATA[Lenstra elliptic curve factorization]]></category>
		<category><![CDATA[Mathematical analysis]]></category>
		<category><![CDATA[Mathematical notation]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Negation]]></category>
		<category><![CDATA[programmer]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Variable]]></category>

		<guid isPermaLink="false">/?p=1937</guid>
		<description><![CDATA[Which is the Fastest Program? When a programmer sees a chunk of code he tends to evaluate it in a rather intuitive manner and to qualify it as &#8220;elegant&#8221; or not. This is quite easy, because it&#8217;s subjective and nobody knows what exactly elegant means. However behind this there is a powerful mathematical approach of &#8230; <a href="/2010/08/29/beginning-algorithm-complexity-and-estimation/" class="more-link">Continue reading <span class="screen-reader-text">Beginning Algorithm Complexity and Estimation</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/09/03/friday-algorithms-input-data-and-complexity/" rel="bookmark" title="Friday Algorithms: Input Data and Complexity">Friday Algorithms: Input Data and Complexity </a></li>
<li><a href="/2010/10/03/using-php-array_diff-in-algorithm-development/" rel="bookmark" title="Using PHP&#8217;s array_diff in Algorithm Development">Using PHP&#8217;s array_diff in Algorithm Development </a></li>
<li><a href="/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/" rel="bookmark" title="How to Check if a Date is More or Less Than a Month Ago with PHP">How to Check if a Date is More or Less Than a Month Ago with PHP </a></li>
<li><a href="/2012/03/12/algorithm-cheatsheet-quicksort/" rel="bookmark" title="Algorithm cheatsheet: Quicksort">Algorithm cheatsheet: Quicksort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Which is the Fastest Program?</h2>
<p><a href="/wp-content/uploads/2010/08/complexity.jpg"><img src="/wp-content/uploads/2010/08/complexity.jpg" alt="" title="circuit" width="430" height="213" class="aligncenter size-full wp-image-1949" srcset="/wp-content/uploads/2010/08/complexity.jpg 430w, /wp-content/uploads/2010/08/complexity-300x148.jpg 300w" sizes="(max-width: 430px) 100vw, 430px" /></a><br />
When a programmer sees a chunk of code he tends to evaluate it in a rather intuitive manner and to qualify it as &#8220;elegant&#8221; or not. This is quite easy, because it&#8217;s subjective and nobody knows what exactly elegant means. However behind this there is a powerful mathematical approach of measuring a program effectiveness.</p>
<p>It&#8217;s a pity that most of the developers still think of the big O notation as something from the university classes, but unusual in the practice and they barely use it their job. But before describing the big O notation, let me start from something really simple.</p>
<p>Let&#8217;s have the following example (note that all the examples are in PHP):</p>
<pre lang="php">
$n = 100;
$s = 0;

for ($i = 0; $i < $n; $i++) {
	for ($j = 0; $j < $n; $j++) {
		$s++;	
	}	
}
</pre>
<p>As you can see there are two assignments and two nested loops. This is really a widely used example from any algorithm book.</p>
<h2>Constants, Languages, Compilers</h2>
<p>First of all the time to assign a value to a variable, to compare two values and to increment a variable is constant. It depends on the computer resources, the compiler or the language, but it's constant on one machine if you compare two chunks of code. Now we can see that these operations take (add) constant time to the program, and we can assume this time is respectively a, b, c, d, e, f, g, h, i.</p>
<pre lang="php">
$n = 100; 	// a
$s = 0;		// b
$i = 0; 	// c
$i < $n; 	// d
$i++;		// e
$j = 0; 	// f
$j < $n;	// g
$j++;		// h
$s++;		// i
</pre>
<h2>What Matters?</h2>
<p>Actually the most important thing here is the value of n. By assigning greater values to n the more time will take the program to run. As we can see from the following table by multiplying the value of n by 10, the time became 100 times more.</p>
<pre lang="php">
n		time
10		0.00002
100		0.002
...		...
</pre>
<p>What happens in fact is that we can sum all these values.</p>
<pre lang="php">
a + b + c + n*d + n*e + n*(f + n*g + n*h + n*i)
</pre>
<p>and by substituting:</p>
<pre lang="php">
a + b + c = k
d + e + n = l
g + h + i = m
</pre>
<p>the result is:</p>
<pre lang="php">
m*n² + l*n + k
</pre>
<h2>Conclusion</h2>
<p>Here the most important thing is the degree of n, because it can change dramatically the program time consumption depending on the n value. Thus this chunk has a quadratic complexity or O(n²).</p>
<p>Of course there are constants, but in the practice they are not so important. Take a look at these two functions:</p>
<pre lang="php">
f = 2*n²
g = 200*n
</pre>
<p>OK, for n = 1 the first one will be faster, but as n increments the second function becomes to be faster and faster, thus after a given value of n the second function is really the fastest!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/09/03/friday-algorithms-input-data-and-complexity/" rel="bookmark" title="Friday Algorithms: Input Data and Complexity">Friday Algorithms: Input Data and Complexity </a></li>
<li><a href="/2010/10/03/using-php-array_diff-in-algorithm-development/" rel="bookmark" title="Using PHP&#8217;s array_diff in Algorithm Development">Using PHP&#8217;s array_diff in Algorithm Development </a></li>
<li><a href="/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/" rel="bookmark" title="How to Check if a Date is More or Less Than a Month Ago with PHP">How to Check if a Date is More or Less Than a Month Ago with PHP </a></li>
<li><a href="/2012/03/12/algorithm-cheatsheet-quicksort/" rel="bookmark" title="Algorithm cheatsheet: Quicksort">Algorithm cheatsheet: Quicksort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/08/29/beginning-algorithm-complexity-and-estimation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
