<?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>Combinatorics &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/combinatorics/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: Bucket Sort</title>
		<link>/2013/01/02/computer-algorithms-bucket-sort/</link>
		<comments>/2013/01/02/computer-algorithms-bucket-sort/#comments</comments>
		<pubDate>Wed, 02 Jan 2013 08:44:30 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[Bucket]]></category>
		<category><![CDATA[Bucket sort]]></category>
		<category><![CDATA[Combinatorics]]></category>
		<category><![CDATA[Counting sort]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[linear sorting algorithm]]></category>
		<category><![CDATA[linear time sorting algorithms]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Order theory]]></category>
		<category><![CDATA[Radix sort]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[two linear time sorting algorithms]]></category>

		<guid isPermaLink="false">/?p=3526</guid>
		<description><![CDATA[Introduction What’s the fastest way to sort the following sequence [9, 3, 0, 5, 4, 1, 2, 6, 8, 7]? Well, the question is a bit tricky since the input is somehow “predefined”. First of all we have only integers, and fortunately they are all different. That’s great and we know that in practice it’s &#8230; <a href="/2013/01/02/computer-algorithms-bucket-sort/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Bucket Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/12/24/computer-algorithms-sorting-in-linear-time/" rel="bookmark" title="Computer Algorithms: Sorting in Linear Time">Computer Algorithms: Sorting in Linear Time </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>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2012/02/20/computer-algorithms-bubble-sort/" rel="bookmark" title="Computer Algorithms: Bubble Sort">Computer Algorithms: Bubble Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>What’s the fastest way to sort the following sequence [9, 3, 0, 5, 4, 1, 2, 6, 8, 7]? Well, the question is a bit tricky since the input is somehow “predefined”. First of all we have only integers, and fortunately they are all different. That’s great and we know that in practice it’s almost impossible to count on such lucky coincidence. However here we can sort the sequence very quickly.</p>
<p>First of all we can pass through all these integers and by using an auxiliary array we can just put them at their corresponding index. We know in advance that that is going to work really well, because they are all different.</p>
<p><img src="https://docs.google.com/drawings/pub?id=1Aoz2O_azhtnea-w_sVma0VRFD0x3QA1Qc2TfZkW1vk8&amp;w=620&amp;h=399"></p>
<p>There is only one major problem in this solution. That’s because we assume all the integers are different. If not – we can just put all them in one single corresponding index.</p>
<p><img src="https://docs.google.com/drawings/pub?id=19NfzaQptazKwjjCOfoukXpbcL4ygNZUq5uXaUm7c3Mk&amp;w=620&amp;h=399"></p>
<p>That is why we can use bucket sort.</p>
<h2>Overview</h2>
<p>Bucket sort it’s the perfect sorting algorithm for the sequence above. We must know in advance that the integers are fairly well distributed over an interval (i, j). Then we can divide this interval in N equal sub-intervals (or buckets). We’ll put each number in its corresponding bucket. Finally for every bucket that contains more than one number we’ll use some linear sorting algorithm.</p>
<p><img src="https://docs.google.com/drawings/pub?id=19rpn5BY3JJOSpRPAJ9hpAoQeHVymxGxFNueuYCogmI4&amp;w=620&amp;h=399"></p>
<p>The thing is that we know that the integers are well distributed, thus we expect that there won’t be many buckets with more than one number inside.</p>
<p>That is why the sequence [1, 2, 3, 2, 1, 2, 3, 1] won’t be sorted faster than [4, 3, 1, 2, 9, 5, 4, 8].</p>
<h2>Pseudo Code</h2>
<pre>
1. Let n be the length of the input list L;
2. For each element i from L
   2.1. If B[i] is not empty
      2.1.1. Put A[i] into B[i] using insertion sort;
      2.1.2. Else B[i] := A[i] 
3. Concatenate B[i .. n] into one sorted list;
</pre>
<h2>Complexity</h2>
<p>The complexity of bucket sort isn’t constant depending on the input. However in the average case the complexity of the algorithm is O(n + k) where n is the length of the input sequence, while k is the number of buckets. </p>
<p>The problem is that its worst-case performance is O(n^2) which makes it as slow as bubble sort.</p>
<h2>Application</h2>
<p>As the other two linear time sorting algorithms (radix sort and counting sort) bucket sort depends so much on the input. The main thing we should be aware of is the way the input data is dispersed over an interval. </p>
<p>Another crucial thing is the number of buckets that can dramatically improve or worse the performance of the algorithm. </p>
<p>This makes bucket sort ideal in cases we know in advance that the input is well dispersed.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/12/24/computer-algorithms-sorting-in-linear-time/" rel="bookmark" title="Computer Algorithms: Sorting in Linear Time">Computer Algorithms: Sorting in Linear Time </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>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2012/02/20/computer-algorithms-bubble-sort/" rel="bookmark" title="Computer Algorithms: Bubble Sort">Computer Algorithms: Bubble Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2013/01/02/computer-algorithms-bucket-sort/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Sorting in Linear Time</title>
		<link>/2012/12/24/computer-algorithms-sorting-in-linear-time/</link>
		<comments>/2012/12/24/computer-algorithms-sorting-in-linear-time/#comments</comments>
		<pubDate>Mon, 24 Dec 2012 11:23:20 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Binary numeral system]]></category>
		<category><![CDATA[Bucket sort]]></category>
		<category><![CDATA[Combinatorics]]></category>
		<category><![CDATA[Counting sort]]></category>
		<category><![CDATA[faster sorting algorithm]]></category>
		<category><![CDATA[Integer sorting]]></category>
		<category><![CDATA[linear time sorting algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[numeric systems]]></category>
		<category><![CDATA[Order theory]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pigeonhole sort]]></category>
		<category><![CDATA[Radix sort]]></category>
		<category><![CDATA[radix sort algorithm]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[sorting algorithm]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[stable sort algorithm]]></category>
		<category><![CDATA[supporting stable sort algorithm]]></category>

		<guid isPermaLink="false">/?p=3516</guid>
		<description><![CDATA[Radix Sort The first question when we see the phrase “sorting in linear time” should be – where’s the catch? Indeed there’s a catch and the thing is that we can’t sort just anything in linear time. Most of the time we can speak on sorting integers in linear time, but as we can see &#8230; <a href="/2012/12/24/computer-algorithms-sorting-in-linear-time/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Sorting in Linear Time</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2013/01/02/computer-algorithms-bucket-sort/" rel="bookmark" title="Computer Algorithms: Bucket Sort">Computer Algorithms: Bucket Sort </a></li>
<li><a href="/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/" rel="bookmark" title="Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort!">Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort! </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="/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>Radix Sort</h2>
<p>The first question when we see the phrase “sorting in linear time” should be – where’s the catch? Indeed there’s a catch and the thing is that we can’t sort just anything in linear time. Most of the time we can speak on sorting integers in linear time, but as we can see later this is not the only case. </p>
<p>Since we speak about integers, we can think of a faster sorting algorithm than usual. Such an algorithm is the counting sort, which can be very fast in some cases, but also very slow in others, so it can be used carefully. Another linear time sorting algorithm is radix sort.</p>
<h2>Introduction</h2>
<p>Count sort is absolutely brilliant and easy to implement. In case we sort integers in the range [n, m] on the first pass we just initialize a zero filled array with length m-n. Than on the second pass we “count” the occurrence of each integer. On the third pass we just sort the integers with an ease. </p>
<p><img src="https://docs.google.com/drawings/pub?id=1VOyJ9u_sp5YQB6gpt0bcWFOKjYTSugoQWJYRkFFZTLc&amp;w=620&amp;h=399"></p>
<p>However we have some problems with that algorithm. What if we have only few items to sort that are very far from each other like [2, 1, 10000000, 2]. This will result in a very large unused data. So we need a dense integer sequence. This is important because we must know in advance the nature of the sequence which is rarely sure.</p>
<p>That’s why we need to use another linear time sorting algorithm for integers that doesn’t have this disadvantage. Such an algorithm is the radix sort.</p>
<h2>Overview</h2>
<p>The idea behind the radix sort is simple. We must look at our “integer” sequence as a string sequence. OK, to become clearer let me give you an example. Our sequence is [12, 2, 23, 33, 22]. First we take the leftmost digit of each number. Thus we must compare [_2, 2, _3, _3, _2]. Clearly we can assume that since the second number “2” is only a one digit number we can fill it up with a leading “0”, to become 02 or _2 in our example: [_2, _2, _3, _3, _2]. Now we sort this sequence with a stable sort algorithm.</p>
<h3>What is a Stable Sort Algorithm</h3>
<p>A stable sort algorithm is an algorithm that sorts a list by preserving the positions of the elements in case they are equal. In terms of PHP this means that:</p>
<pre lang="PHP">
array(0 => 12, 1=> 13, 2 => 12); 
</pre>
<p>Will be sorted as follows:</p>
<pre lang="PHP">
array(0 => 12, 2 => 12, 1 => 13);
</pre>
<p>Thus the third element becomes second following the first element. Note that the third and the first element are equal, but the third appears later in the sequence so it remains later in the sorted sequence.</p>
<p>In the radix sort example, we need a stable sort algorithm, because we need to worry about only one position of digit we explore.</p>
<p>So what happens in our example after we sort the sequence? </p>
<p><img src="https://docs.google.com/drawings/pub?id=10dVPfCVf8YI2sEJNuAujnrOx0g0RxWGsQdTJ0xqGt1k&amp;w=620&amp;h=399"></p>
<p>As we can see we’re far from a sorted sequence, but what if we proceed with the next “position” &#8211; the decimal digit?</p>
<p>Than we end up with this:</p>
<p><img src="https://docs.google.com/drawings/pub?id=1oaKToHilxrKyGJzwm7NvmrSaL3uVRO3R7r0RCb0jrR4&amp;w=621&amp;h=264"></p>
<p>Now we have a sorted sequence, so let’s summarize the algorithm in a short pseudo code.</p>
<h2>Pseudo Code</h2>
<p>The simple approach behind the radix sort algorithm can be described as pseudo code, assuming that we’re sorting decimal integers.</p>
<p>1. For each digit at position 10^0 to 10^n<br />
   1.1. Sort the numbers by this digit using a stable sort algorithm; </p>
<p>The thing is that here we talk about decimal, but actually this algorithm can be applied equally on any numeric systems. That is why it’s called “radix” sort. </p>
<p>Thus we can sort binary numbers, hexadecimals etc.</p>
<p>It’s important to note that this algorithm can be also used to sort strings alphabetically.</p>
<pre>
[ABC, BBC, ABA, AC]
[__C, __C, __A, __C] => [ABA, ABC, BBC, AC]
[_B_, _B_, _B_, _A_] => [AC, ABA, ABC, BBC]
[___, A__, A__, B__] => [AC, ABA, ABC, BBC]
</pre>
<p>That is simply correct because we can assume that our alphabet is another 27 digit numeric system (in case of the Latin alphabet).</p>
<h2>Complexity</h2>
<p>As I said in the beginning radix sort is a linear time sorting algorithm. Let’s see why. First we depend on the numeric system. Let’s assume we have a decimal numeric system – then we have N passes sorting 10 digits which is simply 10*N. In case of K digit numeric system our algorithm will be O(K*N) which is linear.</p>
<p>However you must note that in case we sort N numbers in an N digit numeric system the complexity will become O(N^2)!</p>
<p>We must also remember that in order to implement radix sort and a supporting stable sort algorithm we need an extra space.</p>
<h2>Application</h2>
<p>Sorting integers can be faster than sorting just anything, so any time we need to implement a sorting algorithm we must carefully investigate the input data. And that’s also the big disadvantage of this algorithm – we must know the input in advance, which is rarely the case.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2013/01/02/computer-algorithms-bucket-sort/" rel="bookmark" title="Computer Algorithms: Bucket Sort">Computer Algorithms: Bucket Sort </a></li>
<li><a href="/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/" rel="bookmark" title="Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort!">Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort! </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="/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>/2012/12/24/computer-algorithms-sorting-in-linear-time/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Graph Depth-First Search</title>
		<link>/2012/09/17/computer-algorithms-graph-depth-first-search/</link>
		<comments>/2012/09/17/computer-algorithms-graph-depth-first-search/#comments</comments>
		<pubDate>Mon, 17 Sep 2012 10:52:59 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[Combinatorics]]></category>
		<category><![CDATA[Connectivity]]></category>
		<category><![CDATA[Depth-first search]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[graph-walk algorithm]]></category>
		<category><![CDATA[In-place algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[specific algorithms]]></category>
		<category><![CDATA[two main algorithms]]></category>
		<category><![CDATA[USD]]></category>

		<guid isPermaLink="false">/?p=3340</guid>
		<description><![CDATA[Introduction Along with breadth-first search, depth-first search is one of the two main methods to walk through a graph. This approach though is different. Breadth-first search (BFS) looks pretty much like starting from a vertex and expanding the searching process level by level. This means that first we get some information of all the successors &#8230; <a href="/2012/09/17/computer-algorithms-graph-depth-first-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Graph Depth-First Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/09/24/computer-algorithms-graph-best-first-search/" rel="bookmark" title="Computer Algorithms: Graph Best-First Search">Computer Algorithms: Graph Best-First Search </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Along with <a title="Computer Algorithms: Graph Breadth First Search" href="/2012/09/10/computer-algorithms-graph-breadth-first-search/">breadth-first search</a>, depth-first search is one of the two main methods to walk through a graph. This approach though is different. Breadth-first search (BFS) looks pretty much like starting from a vertex and expanding the searching process level by level. This means that first we get some information of all the successors of the given node and then we go further with the next level. In other words BFS is like a wave. Depth-first search is based on a different approach, which can be very useful in some specific algorithms.</p>
<figure id="attachment_3348" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/1.-DFS-vs.-BFS.png"><img class="size-full wp-image-3348" title="DFS vs. BFS" src="/wp-content/uploads/2012/09/1.-DFS-vs.-BFS.png" alt="DFS vs. BFS" width="621" height="351" srcset="/wp-content/uploads/2012/09/1.-DFS-vs.-BFS.png 621w, /wp-content/uploads/2012/09/1.-DFS-vs.-BFS-300x169.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Depth-first and breadth-first search are the two main ways to explore a graph!</figcaption></figure>
<p>Both methods can be useful in solving different tasks.<span id="more-3340"></span></p>
<h2>Overview</h2>
<p>Depth-first search is an algorithm that by given starting and target node, finds a path between them. We can use DFS also to walk through all the vertices of a graph, in case the graph is connected.</p>
<figure id="attachment_3350" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/09/2.-DFS-explained.png"><img class="size-full wp-image-3350" title="DFS explained" src="/wp-content/uploads/2012/09/2.-DFS-explained.png" alt="DFS explained" width="621" height="351" srcset="/wp-content/uploads/2012/09/2.-DFS-explained.png 621w, /wp-content/uploads/2012/09/2.-DFS-explained-300x169.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">The algorithm frist goes in depth and then backtracks to all unvisited successors!</figcaption></figure>
<p>The whole idea of this algorithm is to go as far as possible from the given starting node searching for the target. In case we get to a node that has no successors, we get back (typically this is done recursively) and we continue with the last vertex that isn’t visited yet.</p>
<p>So basically we have 3 steps:</p>
<ol>
<li>Pick up a vertex that isn&#8217;t visited yet and mark it visited;</li>
<li>Go to its first non-visited successor and mark it visited;</li>
<li>If all the successors of the vertex are already visited or it doesn&#8217;t have successors &#8211; go back to its parent;</li>
</ol>
<h2>Code</h2>
<p>The following <a href="/category/php/" title="PHP on Stoimen.com">PHP</a> code implements the depth-first search. The key point is the recursion in the method depthFirst.</p>
<pre lang="PHP">
class Graph 
{
    protected $_len = 0;
    protected $_g = array();
    protected $_visited = array();
    
    public function __construct()
    {
        $this->_g = array(
            array(0, 1, 1, 0, 0, 0),
            array(1, 0, 0, 1, 0, 0),
            array(1, 0, 0, 1, 1, 1),
            array(0, 1, 1, 0, 1, 0),
            array(0, 0, 1, 1, 0, 1),
            array(0, 0, 1, 0, 1, 0),
        );
        
        $this->_len = count($this->_g);
        
        $this->_initVisited();
    }
    
    protected function _initVisited()
    {
        for ($i = 0; $i < $this->_len; $i++) {
            $this->_visited[$i] = 0;
        }
    }
    
    public function depthFirst($vertex)
    {
        $this->_visited[$vertex] = 1;
    
        echo $vertex . "\n";
        
        for ($i = 0; $i < $this->_len; $i++) {
            if ($this->_g[$vertex][$i] == 1 && !$this->_visited[$i]) {
                $this->depthFirst($i);
            }
        }
    }
}

$g = new Graph();
// 2 0 1 3 4 5
$g->depthFirst(2);
</pre>
<h2>Complexity</h2>
<p>By using an adjacency matrix we need n<sup>2</sup> space for a graph with <strong>n</strong> vertices. We also use an additional array to mark visited vertices, which requires additional space of <strong>n</strong>! Thus the space complexity is O(n<sup>2</sup>).</p>
<p>When it comes to time complexity since we have a recursion and we try visiting all the vertices on each step, the worst-case time is yet again O(n<sup>2</sup>)!</p>
<h2>Application</h2>
<p>This graph-walk algorithm can be very useful when solving some specific tasks like finding the shortest/longest paths in a graph. Although <a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" title="Computer Algorithms: Graph Breadth First Search">BFS</a> and DFS aren&#8217;t the only methods of walking through a graph, they are considered the two main algorithms of that kind. This is important in order to solve graph-based problems.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/09/24/computer-algorithms-graph-best-first-search/" rel="bookmark" title="Computer Algorithms: Graph Best-First Search">Computer Algorithms: Graph Best-First Search </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/09/17/computer-algorithms-graph-depth-first-search/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Shell Sort</title>
		<link>/2012/02/27/computer-algorithms-shell-sort/</link>
		<comments>/2012/02/27/computer-algorithms-shell-sort/#comments</comments>
		<pubDate>Mon, 27 Feb 2012 20:44:54 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Adaptive sort]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[Comb sort]]></category>
		<category><![CDATA[Combinatorics]]></category>
		<category><![CDATA[Donald Shell]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[Knuth]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[Order theory]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pratt]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Shell sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>

		<guid isPermaLink="false">/?p=2734</guid>
		<description><![CDATA[Overview Insertion sort is a great algorithm, because it&#8217;s very intuitive and it is easy to implement, but the problem is that it makes many exchanges for each &#8220;light&#8221; element in order to put it on the right place. Thus “light” elements at the end of the list may slow down the performance of insertion &#8230; <a href="/2012/02/27/computer-algorithms-shell-sort/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Shell Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/03/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
<li><a href="/2012/02/13/computer-algorithms-insertion-sort/" rel="bookmark" title="Computer Algorithms: Insertion Sort">Computer Algorithms: Insertion Sort </a></li>
<li><a href="/2013/01/02/computer-algorithms-bucket-sort/" rel="bookmark" title="Computer Algorithms: Bucket Sort">Computer Algorithms: Bucket Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p><a href="/2012/02/13/computer-algorithms-insertion-sort/" title="Computer Algorithms: Insertion Sort">Insertion sort</a> is a great algorithm, because it&#8217;s very intuitive and it is easy to implement, but the problem is that it makes many exchanges for each &#8220;light&#8221; element in order to put it on the right place. Thus “light” elements at the end of the list may slow down the performance of insertion sort a lot. That is why in 1959 <a href="http://en.wikipedia.org/wiki/Donald_Shell" title="Donald Shell" target="_blank">Donald Shell</a> proposed an algorithm that tries to overcome this problem by comparing items of the list that lie far apart.</p>
<figure id="attachment_2796" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/Insertion-Sort-vs.-Shell-Sort.png"><img src="/wp-content/uploads/2012/02/Insertion-Sort-vs.-Shell-Sort.png" alt="Insertion Sort vs. Shell Sort" title="Insertion Sort vs. Shell Sort" width="620" class="size-full wp-image-2796" srcset="/wp-content/uploads/2012/02/Insertion-Sort-vs.-Shell-Sort.png 640w, /wp-content/uploads/2012/02/Insertion-Sort-vs.-Shell-Sort-300x170.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">Insertion sort compares every single item with all the rest elements of the list in order to find its place, while Shell sort compares items that lie far apart. This makes light elements to move faster to the front of the list.</figcaption></figure>
<p>In the other hand it is obvious that by comparing items that lie apart the list can’t be sorted in one pass as insertion sort. That is why on each pass we should use a fixed gap between the items, then decrease the value on every consecutive iteration.<span id="more-2734"></span></p>
<figure id="attachment_2791" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/Shell-Sort.png"><img src="/wp-content/uploads/2012/02/Shell-Sort.png" alt="Shell Sort" title="Shell Sort" width="620" class="size-full wp-image-2791" srcset="/wp-content/uploads/2012/02/Shell-Sort.png 631w, /wp-content/uploads/2012/02/Shell-Sort-190x300.png 190w" sizes="(max-width: 631px) 100vw, 631px" /></a><figcaption class="wp-caption-text">We start to compare items with a fixed gap, that becomes lesser on each iteration until it gets to 1.</figcaption></figure>
<p>However it is intuitively clear that Shell sort may need even more comparisons than insertion sort. Then why should we use it? </p>
<p>The thing is that insertion sort is not an effective sorting algorithm at all, but in some cases, when the list is almost sorted it can be quite useful. Here’s the answer of the question above. With Shell sort once the list is sorted for gap = i, it is sorted for every gap = j, where j < i, and this is its main advantage.

[caption id="attachment_2792" align="alignnone" width="620" caption="Shell sort can make less exchanges than insertion sort."]<a href="/wp-content/uploads/2012/02/Shell-Sort-Principles.png"><img src="/wp-content/uploads/2012/02/Shell-Sort-Principles.png" alt="Shell Sort Principles" title="Shell Sort Principles" width="620" class="size-full wp-image-2792" srcset="/wp-content/uploads/2012/02/Shell-Sort-Principles.png 641w, /wp-content/uploads/2012/02/Shell-Sort-Principles-150x150.png 150w, /wp-content/uploads/2012/02/Shell-Sort-Principles-300x298.png 300w" sizes="(max-width: 641px) 100vw, 641px" /></a>[/caption]</p>
<h3>How to choose gap size</h3>
<p>Not a cool thing about Shell sort is that we’ve to choose “the perfect” gap sequence for our list. However this is not an easy task, because it depends a lot of the input data. The good news is that there are some gap sequences proved to be working well in the general cases.</p>
<h3>Shell Sequence</h3>
<p>Donald Shell proposes a sequence that follows the formula FLOOR(N/2<sup>k</sup>), then for N = 1000, we get the following sequence: [500, 250, 125, 62, 31, 15, 7, 3, 1]</p>
<figure id="attachment_2793" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/Shell-Gap-Sequence.png"><img src="/wp-content/uploads/2012/02/Shell-Gap-Sequence.png" alt="Shell Gap Sequence" title="Shell Gap Sequence" width="620" class="size-full wp-image-2793" srcset="/wp-content/uploads/2012/02/Shell-Gap-Sequence.png 640w, /wp-content/uploads/2012/02/Shell-Gap-Sequence-300x185.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">Shell sequence for N=1000: (500, 250, 125, 62, 31, 15, 7, 3, 1)</figcaption></figure>
<h3>Pratt Sequence</h3>
<p><a href="http://en.wikipedia.org/wiki/Vaughan_Ronald_Pratt" title="Vaughan Pratt" target="_blank">Pratt</a> proposes another sequence that’s growing with a slower pace than the Shell’s sequence. He proposes successive numbers of the form 2<sup>p</sup>3<sup>q</sup> or [1, 2, 3, 4, 6, 8, 9, 12, &#8230;].</p>
<figure id="attachment_2794" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/Pratt-Gap-Sequence.png"><img src="/wp-content/uploads/2012/02/Pratt-Gap-Sequence.png" alt="Pratt Gap Sequence" title="Pratt Gap Sequence" width="620" class="size-full wp-image-2794" srcset="/wp-content/uploads/2012/02/Pratt-Gap-Sequence.png 640w, /wp-content/uploads/2012/02/Pratt-Gap-Sequence-300x185.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">Pratt sequence: (1, 2, 3, 4, 6, 8, 9, 12, ...)</figcaption></figure>
<h3>Knuth Sequence</h3>
<p>Knuth in other hand proposes his own sequence following the formula (3<sup>k</sup> &#8211; 1) / 2 or [1, 4, 14, 40, 121, &#8230;]</p>
<figure id="attachment_2795" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/Knuth-Gap-Sequence.png"><img src="/wp-content/uploads/2012/02/Knuth-Gap-Sequence.png" alt="Knuth Gap Sequence" title="Knuth Gap Sequence" width="620" class="size-full wp-image-2795" srcset="/wp-content/uploads/2012/02/Knuth-Gap-Sequence.png 640w, /wp-content/uploads/2012/02/Knuth-Gap-Sequence-300x185.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">Knuth sequence: (1, 4, 13, 40, 121, ...)</figcaption></figure>
<p>Of course there are many other gap sequences, proposed by various developers and researchers, but the problem is that the effectiveness of the algorithm strongly depends on the input data. But before taking a look to the complexity of Shell sort, let’s see first its implementation.</p>
<h2>Implementation</h2>
<p>Here’s a Shell sort implementation on <a href="/category/php/" title="PHP on stoimen.com">PHP</a> using the Pratt gap sequence. The thing is that for this data set other gap sequences may appear to be better solution.</p>
<pre lang="php">
$input = array(6, 5, 3, 1, 8, 7, 2, 4);

function shell_sort($arr)
{
	$gaps = array(1, 2, 3, 4, 6);
	$gap  = array_pop($gaps);
	$len  = count($arr);
	
	while($gap > 0)
	{
		for($i = $gap; $i < $len; $i++) {
			
			$temp = $arr[$i];
			$j = $i;
			
			while($j >= $gap && $arr[$j - $gap] > $temp) {
				$arr[$j] = $arr[$j - $gap];
				$j -= $gap;
			}
			
			$arr[$j] = $temp;
		}
		
		$gap = array_pop($gaps);
	}
	
	return $arr;
}

// 1, 2, 3, 4, 5, 6, 7, 8
shell_sort($input);
</pre>
<p>It&#8217;s easy to change this code in order to work with Shell sequence.</p>
<pre lang="PHP">
$input = array(6, 5, 3, 1, 8, 7, 2, 4);

function shell_sort($arr)
{
        $len  = count($arr);
	$gap  = floor($len/2);
	
	while($gap > 0)
	{
		for($i = $gap; $i < $len; $i++) {
			
			$temp = $arr[$i];
			$j = $i;
			
			while($j >= $gap && $arr[$j - $gap] > $temp) {
				$arr[$j] = $arr[$j - $gap];
				$j -= $gap;
			}
			
			$arr[$j] = $temp;
		}
		
		$gap = floor($gap/2);
	}
	
	return $arr;
}

// 1, 2, 3, 4, 5, 6, 7, 8
shell_sort($input);
</pre>
<h2>Complexity</h2>
<p>Yet again we can’t determine the exact complexity of this algorithm, because it depends on the gap sequence. However we may say what is the complexity of Shell sort with the sequences of Knuth, Pratt and Donald Shell. For the Shell&#8217;s sequence the complexity is O(n<sup>2</sup>), while for the Pratt’s sequence it is O(n*log<sup>2</sup>(n)). The best approach is the Knuth sequence where the complexity is O(n<sup>3/2</sup>), as you can see on the diagram bellow.</p>
<figure id="attachment_2797" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/Complexity-of-Shell-Sort.png"><img src="/wp-content/uploads/2012/02/Complexity-of-Shell-Sort.png" alt="Complexity of Shell Sort" title="Complexity of Shell Sort" width="620" class="size-full wp-image-2797" srcset="/wp-content/uploads/2012/02/Complexity-of-Shell-Sort.png 640w, /wp-content/uploads/2012/02/Complexity-of-Shell-Sort-300x185.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">Complexity of Shell sort with different gap sequences.</figcaption></figure>
<h2>Application</h2>
<p>Well, as insertion sort and bubble sort, Shell sort is not very effective compared to quicksort or merge sort. The good thing is that it is quite easy to implement (not easier than insertion sort), but in general it should be avoided for large data sets. Perhaps the main advantage of Shell sort is that the list can be sorted for a gap greater than 1 and thus making less exchanges than insertion sort. </p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/03/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
<li><a href="/2012/02/13/computer-algorithms-insertion-sort/" rel="bookmark" title="Computer Algorithms: Insertion Sort">Computer Algorithms: Insertion Sort </a></li>
<li><a href="/2013/01/02/computer-algorithms-bucket-sort/" rel="bookmark" title="Computer Algorithms: Bucket Sort">Computer Algorithms: Bucket Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/02/27/computer-algorithms-shell-sort/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
