<?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>Recursion &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/recursion/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: Quicksort</title>
		<link>/2012/03/13/computer-algorithms-quicksort/</link>
		<comments>/2012/03/13/computer-algorithms-quicksort/#comments</comments>
		<pubDate>Mon, 12 Mar 2012 21:36:09 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[brilliant sorting algorithm]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[Divide and conquer algorithm]]></category>
		<category><![CDATA[elegant general purpose sorting algorithm]]></category>
		<category><![CDATA[elegant solution]]></category>
		<category><![CDATA[faster algorithms]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[purpose sorting algorithm]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Recursion]]></category>
		<category><![CDATA[recursive solution]]></category>
		<category><![CDATA[Selection algorithm]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Spreadsort]]></category>

		<guid isPermaLink="false">/?p=2899</guid>
		<description><![CDATA[Introduction When it comes to sorting items by comparing them merge sort is one very natural approach. It is natural, because simply divides the list into two equal sub-lists then sort these two partitions applying the same rule. That is a typical divide and conquer algorithm and it just follows the intuitive approach of speeding &#8230; <a href="/2012/03/13/computer-algorithms-quicksort/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Quicksort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/06/18/friday-algorithms-iterative-quicksort/" rel="bookmark" title="Friday Algorithms: Iterative Quicksort">Friday Algorithms: Iterative Quicksort </a></li>
<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="/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/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>When it comes to sorting items by comparing them <a href="/2012/03/05/computer-algorithms-merge-sort/" title="Computer Algorithms: Merge Sort">merge sort</a> is one very natural approach. It is natural, because simply divides the list into two equal sub-lists then sort these two partitions applying the same rule. That is a typical divide and conquer algorithm and it just follows the intuitive approach of speeding up the sorting process by reducing the number of comparisons. However there are other “divide and conquer” sorting algorithms that do not follow the merge sort scheme, while they have practically the same success. Such an algorithm is quicksort.</p>
<h2>Overview</h2>
<p>Back in 1960 <a href="http://en.wikipedia.org/wiki/Tony_Hoare" title="C. A. R. Hoare" target="_blank">C. A. R. Hoare</a> comes with a brilliant sorting algorithm. In general quicksort consists of some very simple steps. First we’ve to choose an element from the list (called a pivot) then we must put all the elements with value less than the pivot on the left side of the pivot and all the items with value greater than the pivot on its right side. After that we must repeat these steps for the left and the right sub-lists. That is quicksort! Simple and elegant! </p>
<p><figure id="attachment_2908" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/Quicksort.png"><img src="/wp-content/uploads/2012/03/Quicksort.png" alt="Quicksort" title="Quicksort" width="620" height="399" class="size-full wp-image-2908" srcset="/wp-content/uploads/2012/03/Quicksort.png 620w, /wp-content/uploads/2012/03/Quicksort-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure><span id="more-2899"></span></p>
<p>It is a pure divide and conquer approach as merge sort, but while merge sort’s tricky part was merging the sorted sub-lists, in quicksort there are other things to consider. </p>
<p>First of all obviously the choice of a pivot is the bottleneck. Indeed it all depends on that pivot. Imagine that you choose the greatest value from the list &#8211; than you’ve to put all the other items of the list into the “left” sub-list. If you do that on each step you’ll practically go into the worst scenario and that is no good. The thing is that in the worst case quicksort is not so effective and it’s practically as slow as bubble sort and insertion sort. The good thing is that in practice with randomly generated lists there is not a high possibility to go into the worst case of quicksort.</p>
<h3>Choosing a pivot</h3>
<p>Of course the best pivot is the middle element from the list. Thus the list will be divided into two fairly equal sub-lists. The problem is that there’s not an easy way to get the middle element from a list and this will slow down the algorithm. So typically we can get for a pivot the first or the last item of the list.</p>
<p>After choosing a pivot the rest is simple. Put every item with a greater value on the right and every item with a lesser value on the left. Then we must sort the left and right sub-lists just as we did with the initial list. </p>
<p><a href="/wp-content/uploads/2012/03/MerginginQuicksort.png"><img src="/wp-content/uploads/2012/03/MerginginQuicksort.png" alt="Merging in Quicksort" title="Merging in Quicksort" width="620" height="399" class="alignnone size-full wp-image-2910" srcset="/wp-content/uploads/2012/03/MerginginQuicksort.png 620w, /wp-content/uploads/2012/03/MerginginQuicksort-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a></p>
<p>It’s clear that with this algorithm naturally we’re going into a recursive solution. Typically every divide and conquer approach is easy to implement with recursion. But because recursion can be heavy, there is an iterative approach.</p>
<h2>Implementation</h2>
<p>As I said above recursive approach is something very natural for quicksort as it follows the divide and conquer principles. On each step we divide the list in two and we pass those sub-lists to our recursive function. But recursion is dangerous sometimes, so an iterative approach is also available. Typically iterative approaches “model” recursion with extra memory and a model of a stack, which is our case. Here we have two examples of quicksort &#8211; recursive and iterative in PHP. Let’s go first with the recursion.</p>
<h3>Recursive Quicksort</h3>
<pre lang="PHP">
$list = array(5,3,9,8,7,2,4,1,6,5);
 
// recursive
function quicksort($array)
{
	if (count($array) == 0) {
    	return array();
	}
 
	$pivot = $array[0];
	$left = $right = array();
 
	for ($i = 1; $i < count($array); $i++) {
		if ($array[$i] < $pivot) {
			$left[] = $array[$i];
		} else {
			$right[] = $array[$i];
		}
	}
	
	return array_merge(quicksort($left), array($pivot), quicksort($right));
}

// 1, 2, 3, 4, 5, 5, 6, 7, 8, 9
print_r(quicksort($list));
</pre>
<h3>Iterative Quicksort</h3>
<pre lang="PHP">
$list = array(5,3,9,8,7,2,4,1,6,5);

// iterative
function quicksort_iterative($array)
{
    $stack = array($array);
    $sorted = array();
 
    while (count($stack) > 0) {
 
        $temp = array_pop($stack);
 
        if (count($temp) == 1) {
            $sorted[] = $temp[0];
            continue;
        }
 
        $pivot = $temp[0];
        $left = $right = array();
 
        for ($i = 1; $i < count($temp); $i++) {
            if ($pivot > $temp[$i]) {
                $left[] = $temp[$i];
            } else {
                $right[] = $temp[$i];
            }
        }
 
        $left[] = $pivot;
 
        if (count($right))
            array_push($stack, $right);
        if (count($left))
            array_push($stack, $left);
    }
 
    return $sorted;
}

// 1, 2, 3, 4, 5, 5, 6, 7, 8, 9
print_r(quicksort_iterative($list));
</pre>
<h2>Complexity</h2>
<p>The complexity of quicksort in the average case is O(n*log(n)) - same as Merge sort. The problem is that in the worst case it is O(n<sup>2</sup>) - same as bubble sort. Obviously the worst case is when we have an already sorted list, and we constantly take for a pivot the last element of the list. But we should consider that in practice we don’t quite use sorted lists that we have to sort again, right?</p>
<p><a href="/wp-content/uploads/2012/03/Quicksort.Average.Worst_.png"><img src="/wp-content/uploads/2012/03/Quicksort.Average.Worst_.png" alt="Quicksort average and worst case scenarios" title="Quicksort.Average.Worst" width="600" height="371" class="alignnone size-full wp-image-2909" srcset="/wp-content/uploads/2012/03/Quicksort.Average.Worst_.png 600w, /wp-content/uploads/2012/03/Quicksort.Average.Worst_-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a></p>
<h2>Application</h2>
<p>Quicksort is a great sorting algorithm and developers often go for it, but let's see some pros and cons of it.</p>
<h3>Why using quicksort</h3>
<ol>
<li>Recursive implementation is easy</li>
<li>In general its speed is same as merge sort - O(n*log(n))</li>
<li>Elegant solution with no tricky merging as merge sort</li>
</ol>
<h3>Why not using quicksort</h3>
<ol>
<li>As slow as bubble sort in the worst case!</li>
<li>Iterative implementation isn't easy</li>
<li>There are faster algorithms for some sets of data types</li>
</ol>
<p>Quicksort is beautiful because of the elegant idea behind its principles. Indeed if you have two sorted lists one with items with a greater value from a given value and the other with items smaller form that given value you can simply concatenate them and you can be sure that the resulting list will be sorted with no need of special merge. </p>
<p>In fact quicksort is a very elegant general purpose sorting algorithm and every developer should be familiar with its principles.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/06/18/friday-algorithms-iterative-quicksort/" rel="bookmark" title="Friday Algorithms: Iterative Quicksort">Friday Algorithms: Iterative Quicksort </a></li>
<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="/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/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/03/13/computer-algorithms-quicksort/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Binary Search</title>
		<link>/2011/12/26/computer-algorithms-binary-search/</link>
		<comments>/2011/12/26/computer-algorithms-binary-search/#comments</comments>
		<pubDate>Mon, 26 Dec 2011 13:14:25 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search algorithm]]></category>
		<category><![CDATA[Control flow]]></category>
		<category><![CDATA[famous and best suitable search algorithm]]></category>
		<category><![CDATA[Fibonacci number]]></category>
		<category><![CDATA[Fibonacci search algorithm]]></category>
		<category><![CDATA[Fibonacci search technique]]></category>
		<category><![CDATA[Golden section search]]></category>
		<category><![CDATA[golden section search algorithm]]></category>
		<category><![CDATA[Jump search]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Recursion]]></category>
		<category><![CDATA[Recursion theory]]></category>
		<category><![CDATA[recursive and iterative solution]]></category>
		<category><![CDATA[search algorithm]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[suitable search algorithm]]></category>
		<category><![CDATA[Theoretical computer science]]></category>
		<category><![CDATA[two algorithms]]></category>

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

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

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

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

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

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

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