<?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>Selection algorithm &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/selection-algorithm/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: Order Statistics</title>
		<link>/2012/05/28/computer-algorithms-order-statistics-the-algorithm/</link>
		<comments>/2012/05/28/computer-algorithms-order-statistics-the-algorithm/#respond</comments>
		<pubDate>Mon, 28 May 2012 19:37:00 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Best worst and average case]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Selection algorithm]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[then search]]></category>

		<guid isPermaLink="false">/?p=3149</guid>
		<description><![CDATA[Introduction We know that finding the minimum in a list of integers is a fairly simple task, but what about finding the i-th smallest element? Then the task isn’t that trivial and we have to think for a different approach. First of all there are some very basic and intuitive approaches. Since finding the minimum &#8230; <a href="/2012/05/28/computer-algorithms-order-statistics-the-algorithm/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Order Statistics</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: 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>
<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/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>We know that <a href="/2012/05/21/computer-algorithms-minimum-and-maximum/" title="Computer Algorithms: Minimum and Maximum">finding the minimum in a list of integers</a> is a fairly simple task, but what about finding the i-th smallest element? Then the task isn’t that trivial and we have to think for a different approach. </p>
<p>First of all there are some very basic and intuitive approaches. Since finding the minimum is so easy, can we just find the minimum, than exclude it from the list and then search the minimum again until we find the i-th smallest element.</p>
<p><figure id="attachment_3164" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/1.-Finding-the-Minimums.png"><img src="/wp-content/uploads/2012/05/1.-Finding-the-Minimums.png" alt="Finding the Minimums" title="Finding the Minimums" width="621" height="302" class="size-full wp-image-3164" srcset="/wp-content/uploads/2012/05/1.-Finding-the-Minimums.png 621w, /wp-content/uploads/2012/05/1.-Finding-the-Minimums-300x145.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text"> </figcaption></figure><span id="more-3149"></span></p>
<p>That is a pure brute-force-like algorithm and it is extremely slow. In this case if we’re looking for the 99-th smallest element into an array of 100 items it will be quite inefficient. In other words this isn’t the best approach.</p>
<p>Another fairly intuitive approach is to sort the list in first place and then search the i-th element. </p>
<figure id="attachment_3163" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/2.-Sort-and-Seach.png"><img src="/wp-content/uploads/2012/05/2.-Sort-and-Seach.png" alt="Sort and Seach" title="Sort and Seach" width="621" height="299" class="size-full wp-image-3163" srcset="/wp-content/uploads/2012/05/2.-Sort-and-Seach.png 621w, /wp-content/uploads/2012/05/2.-Sort-and-Seach-300x144.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">First we can sort the list and then search for the i-th element!</figcaption></figure>
<p>This is better than the our first attempt because we&#8217;ll need the time to sort the array and then search (in linear time) the i-th element.</p>
<p>In this case we need to find out which of the sorting algorithms we will use. Will it be <a href="/2012/03/05/computer-algorithms-merge-sort/" title="Computer Algorithms: Merge Sort">merge sort</a> (with constant O(n.lg(n)) complexity) or <a href="/2012/03/13/computer-algorithms-quicksort/" title="Computer Algorithms: Quicksort">quicksort</a> (with O(n<sup>2</sup>) in the worst case, but O(n.lg(n)) average complexity) or <a href="/2012/02/20/computer-algorithms-bubble-sort/" title="Computer Algorithms: Bubble Sort">bubble sort</a> (O(n^n) in the best-case scenario) it’s a developer choice.</p>
<p>However there is one very clever and yet more efficient approach, based on some observations.</p>
<h2>Overview</h2>
<p>If we’re looking for the i-th element and we decided that the list must be sorted first, we don’t need to fully sort it in order to find the desired element. </p>
<p>In case the list is sorted it’s easy to find which is the i-th element. However if the i-th element is in its place, the only thing we need to know is that the items on the left side of the i-th element are smaller and the items on the right side are greater. We don’t need the left and the right side ordered.</p>
<figure id="attachment_3162" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/3.-Dont-need-ordered-sub-lists.png"><img src="/wp-content/uploads/2012/05/3.-Dont-need-ordered-sub-lists.png" alt="Don&#039;t need ordered sub-lists" title="Don&#039;t need ordered sub-lists" width="619" height="279" class="size-full wp-image-3162" srcset="/wp-content/uploads/2012/05/3.-Dont-need-ordered-sub-lists.png 619w, /wp-content/uploads/2012/05/3.-Dont-need-ordered-sub-lists-300x135.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>In the other hand this approach looks very much like quicksort. There during the sorting process we put the items smaller than the “pivot” on its left and the items greater than the pivot on its right. After that partitioning we executed quicksort on the left and on the right sub-lists.</p>
<p>Here the approach is similar with very small changes. First we choose a pivot. Then we make two partitions of the list &#8211; one left sub-list with all the elements with smaller values than the pivot and one right sub-list with all the elements with a greater value than the pivot. </p>
<figure id="attachment_3161" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/4.-Choose-a-pivot-and-partition.png"><img src="/wp-content/uploads/2012/05/4.-Choose-a-pivot-and-partition.png" alt="Choose a pivot and partition" title="Choose a pivot and partition" width="618" height="229" class="size-full wp-image-3161" srcset="/wp-content/uploads/2012/05/4.-Choose-a-pivot-and-partition.png 618w, /wp-content/uploads/2012/05/4.-Choose-a-pivot-and-partition-300x111.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Just like quicksort we chose a pivot and then we partition the list into two sub-lists!</figcaption></figure>
<p>Now we check the length of the left sub-list. If it is greater than i we continue recursively with the left sub-list and again we’re searching for the i-th element.</p>
<p>In case the length of the left sub-list is smaller than i, we continue with the right sub-list. However this time we don’t search for the i-th element, but for the i &#8211; length(LEFT). </p>
<h2>Implementation</h2>
<p>The following implementation is in <a href="/category/php/" title="PHP on stoimen.com">PHP</a>. It’s important to note that at each step we need two non-empty sub-list. That is why we take the pivot (by extracting the last item of the list) and then making two sub-lists. In case one of the sub-lists is empty we append the pivot in it. Thus we’re always partitioning the list into two non-empty sub-lists. </p>
<pre lang="PHP">
$list = array(3,4,5,7,8,2,5,6,9,0,1);

function partition($list, $pivot)
{
	$left = $right = array();
	
	$len = count($list);
	for ($i = 0; $i < $len; $i++) {
		if ($list[$i] <= $pivot) {
			$left[] = $list[$i];
		} else {
			$right[] = $list[$i];
		}
	}

	if (count($left) == 0) {
		$left[] = $pivot;
	} else {
		$right[] = $pivot;
	} 
	
	return array($left, $right);
}

function order_statistic($list, $i)
{
	if (count($list) == 1) {
		return $list[0];
	}
	
	// ceate a non empty partitions
	// extract the pivot from the list and
	// in case one of the sub-lists is empty
	// add the pivot there!
	$pivot = array_pop($list);
	list($left, $right) = partition($list, $pivot);
	
	if (count($left) >= $i) {
		return order_statistic($left, $i);
	} else {
		return order_statistic($right, $i - count($left));
	}
}

// 4
echo order_statistic($list, 5);
</pre>
<h2>Application</h2>
<p>Finding the minimum and maximum is easy, however sometimes we don&#8217;t search for them, but for the second, third or i-th smallest element. Then our task becomes a bit more difficult. This algorithm can be useful in many practical cases and shows us how different kind of algorithms may be related &#8211; exactly as this algorithm is related to quicksort in its principles.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: 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>
<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/02/20/computer-algorithms-bubble-sort/" rel="bookmark" title="Computer Algorithms: Bubble Sort">Computer Algorithms: Bubble Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/05/28/computer-algorithms-order-statistics-the-algorithm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Minimum and Maximum</title>
		<link>/2012/05/21/computer-algorithms-minimum-and-maximum/</link>
		<comments>/2012/05/21/computer-algorithms-minimum-and-maximum/#comments</comments>
		<pubDate>Mon, 21 May 2012 20:14:30 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Application This algorithm]]></category>
		<category><![CDATA[Calculus]]></category>
		<category><![CDATA[comparisons solution]]></category>
		<category><![CDATA[Counting sort]]></category>
		<category><![CDATA[Mathematical analysis]]></category>
		<category><![CDATA[Mathematical optimization]]></category>
		<category><![CDATA[Maxima and minima]]></category>
		<category><![CDATA[memory solution]]></category>
		<category><![CDATA[Minima and maxima]]></category>
		<category><![CDATA[Selection algorithm]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[The algorithm]]></category>

		<guid isPermaLink="false">/?p=3134</guid>
		<description><![CDATA[Introduction To find the minimum value into an array of items itsn&#8217;t difficult. There are not many options to do that. The most natural approach is to take the first item and to compare its value against the values of all other elements. Once we find a smaller element we continue the comparisons with its &#8230; <a href="/2012/05/21/computer-algorithms-minimum-and-maximum/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Minimum and Maximum</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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/11/12/computer-algorithms-kruskals-minimum-spanning-tree/" rel="bookmark" title="Computer Algorithms: Kruskal&#8217;s Minimum Spanning Tree">Computer Algorithms: Kruskal&#8217;s Minimum Spanning Tree </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="/2012/11/19/computer-algorithms-prims-minimum-spanning-tree/" rel="bookmark" title="Computer Algorithms: Prim&#8217;s Minimum Spanning Tree">Computer Algorithms: Prim&#8217;s Minimum Spanning Tree </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>To find the minimum value into an array of items itsn&#8217;t difficult. There are not many options to do that. The most natural approach is to take the first item and to compare its value against the values of all other elements. Once we find a smaller element we continue the comparisons with its value. Finally we find the minimum.</p>
<p><a href="/wp-content/uploads/2012/05/1.-Find-a-Minimum.png"><img class="size-full wp-image-3150" title="Find a Minimum" src="/wp-content/uploads/2012/05/1.-Find-a-Minimum.png" alt="Find a Minimum" width="621" height="431" srcset="/wp-content/uploads/2012/05/1.-Find-a-Minimum.png 621w, /wp-content/uploads/2012/05/1.-Find-a-Minimum-300x208.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a></p>
<p>First thing to note is that we pass through the array with <strong>n</strong> steps and we need exactly <strong>n-1</strong> comparisons. It’s clear that this is the optimal solution, because we must check all the elements. For sure we can’t be sure that we’ve found the minimum (maximum) value without checking every single value.<br />
<span id="more-3134"></span></p>
<h2>Overview</h2>
<p>The algorithm above is very simple and we’re sure that it is optimal. Obviously finding both the minimum and the maximum value is O(n) with <strong>n-1</strong> comparisons, but what about combining these tasks into one single pass.</p>
<figure id="attachment_3153" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/2.-Find-a-Maximum.png"><img class="size-full wp-image-3153" title="Find a Maximum" src="/wp-content/uploads/2012/05/2.-Find-a-Maximum.png" alt="Find a Maximum" width="621" height="431" srcset="/wp-content/uploads/2012/05/2.-Find-a-Maximum.png 621w, /wp-content/uploads/2012/05/2.-Find-a-Maximum-300x208.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Finding the maximum is identical to finding the minimum and requires n-1 comparisons!</figcaption></figure>
<p>Since they both are <strong>O(n)</strong> and need <strong>n-1</strong> comparisons it’s natural to think that combining the two tasks will be O(n) and 2n &#8211; 2 comparisons. However we can reduce the number of comparisons!</p>
<p>Instead of taking only one item from the array and comparing it against the minimum and maximum we can take a pair of items at each step. Thus we can first compare them and then compare the smaller value with the currently smallest value and the greater item with the currently greatest value. This will make only 3 comparisons instead of 4.</p>
<p><a href="/wp-content/uploads/2012/05/3.-Find-both-minimum-and-maximum.png"><img class="alignnone size-full wp-image-3155" title="Find both minimum and maximum" src="/wp-content/uploads/2012/05/3.-Find-both-minimum-and-maximum.png" alt="Both minimum and maximum with less comparisons!" width="619" height="383" srcset="/wp-content/uploads/2012/05/3.-Find-both-minimum-and-maximum.png 619w, /wp-content/uploads/2012/05/3.-Find-both-minimum-and-maximum-300x185.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a></p>
<h2>Implementation</h2>
<p>It’s easy to implement the minimum (maximum) algorithms with a single loop.</p>
<p><script src="https://gist.github.com/stoimen/d2d44986bb70a19bc72c.js"></script></p>
<p>The implementation of finding the maximum is practically the same.</p>
<p><script src="https://gist.github.com/stoimen/fff5cb54c413ca332ffb.js"></script></p>
<p>Simply merging these two functions will lead us to a O(n) with 2n &#8211; 2 comparisons solution.</p>
<p><script src="https://gist.github.com/stoimen/82e563992421dc612498.js"></script></p>
<p>However we can take a pair of items on each step. First we’ll compare the items from that pair and after that we’ll compare them respectively with the minimum and the maximum value. Because on each iteration we jump by two items, in case the number of array items is even we must check for the array boundaries. This can be overcome by adding a sentinel. Thus the array items are always odd, but this will lead us to a &#8220;extra&#8221; memory solution.</p>
<h3>Sentinel</h3>
<p><script src="https://gist.github.com/stoimen/4b46f015c096630cd2b1.js"></script></p>
<h3>Without sentinel</h3>
<p><script src="https://gist.github.com/stoimen/a64ac6100e95f63812dc.js"></script></p>
<h2>Complexity</h2>
<p>The complexity of finding both minimum and maximum is O(n). Even after combining the both algorithms in one single pass the complexity remains O(n). However in the second case we can reduce the number of comparisons to 3 * ceil(n/2) instead of 2n &#8211; 2!</p>
<h2>Application</h2>
<p>This algorithm can be applied in various fields of the computer science, since its nature is so basic. However there are two reasons why this approach is so important.</p>
<p>First we can see how by combining two &#8220;algorithms&#8221; doesn’t mean that we combine their complexities or the number of operations. With a clever trick and with the observation that the two operations are related (minimum and maximum) we can reduce the number of comparisons.</p>
<p>In the other hand we see how using a sentinel can be very handy and can spare us some comparisons, just like the <a title="Computer Algorithms: Sequential Search" href="/2011/11/24/computer-algorithms-sequential-search/">sequential search</a>.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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/11/12/computer-algorithms-kruskals-minimum-spanning-tree/" rel="bookmark" title="Computer Algorithms: Kruskal&#8217;s Minimum Spanning Tree">Computer Algorithms: Kruskal&#8217;s Minimum Spanning Tree </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="/2012/11/19/computer-algorithms-prims-minimum-spanning-tree/" rel="bookmark" title="Computer Algorithms: Prim&#8217;s Minimum Spanning Tree">Computer Algorithms: Prim&#8217;s Minimum Spanning Tree </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/05/21/computer-algorithms-minimum-and-maximum/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<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: Interpolation Search</title>
		<link>/2012/01/02/computer-algorithms-interpolation-search/</link>
		<comments>/2012/01/02/computer-algorithms-interpolation-search/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 18:31:42 +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[Binary search tree]]></category>
		<category><![CDATA[even binary search]]></category>
		<category><![CDATA[Interpolation]]></category>
		<category><![CDATA[Interpolation search]]></category>
		<category><![CDATA[interpolation search algorithm]]></category>
		<category><![CDATA[Jump search]]></category>
		<category><![CDATA[Logarithm]]></category>
		<category><![CDATA[search algorithm]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[searching algorithms]]></category>
		<category><![CDATA[Selection algorithm]]></category>
		<category><![CDATA[Technology/Internet]]></category>

		<guid isPermaLink="false">/?p=2560</guid>
		<description><![CDATA[Overview I wrote about binary search in my previous post, which is indeed one very fast searching algorithm, but in some cases we can achieve even faster results. Such an algorithm is the “interpolation search” &#8211; perhaps the most interesting of all searching algorithms. However we shouldn’t forget that the data must follow some limitations. &#8230; <a href="/2012/01/02/computer-algorithms-interpolation-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Interpolation Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </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>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>I wrote about <a title="Computer Algorithms: Binary Search" href="/2011/12/26/computer-algorithms-binary-search/">binary search</a> in my previous post, which is indeed one very fast searching algorithm, but in some cases we can achieve even faster results. Such an algorithm is the “interpolation search” &#8211; perhaps the most interesting of all searching algorithms. However we shouldn’t forget that the data must follow some limitations. In first place the array must be sorted. Also we must know the bounds of the interval.</p>
<p>Why is that? Well, this algorithm tries to follow the way we search a name in a phone book, or a word in the dictionary. We, humans, know in advance that in case the name we’re searching starts with a &#8220;B&#8221;, like &#8220;Bond&#8221; for instance, we should start searching near the beginning of the phone book. Thus if we&#8217;re searching the word “algorithm” in the dictionary, you know that it should be placed somewhere at the beginning. This is because we know the order of the letters, we know the interval (a-z), and somehow we intuitively know that the words are dispersed equally. These facts are enough to realize that the binary search can be a bad choice. Indeed the binary search algorithm divides the list in two equal sub-lists, which is useless if we know in advance that the searched item is somewhere in the beginning or the end of the list. Yes, we can use also <a href="/2011/12/12/computer-algorithms-jump-search/" title="Computer Algorithms: Jump Search">jump search</a> if the item is at the beginning, but not if it is at the end, in that case this algorithm is not so effective.</p>
<p>So the interpolation search is based on some simple facts. The binary search divides the interval on two equal sub-lists, as shown on the image bellow.</p>
<figure id="attachment_2580" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/InterpolationSearchfig.1.png"><img class="size-full wp-image-2580" title="Interpolation Search fig. 1" src="/wp-content/uploads/2012/01/InterpolationSearchfig.1.png" alt="Binary search basic approach" width="620" srcset="/wp-content/uploads/2012/01/InterpolationSearchfig.1.png 959w, /wp-content/uploads/2012/01/InterpolationSearchfig.1-300x79.png 300w" sizes="(max-width: 959px) 100vw, 959px" /></a><figcaption class="wp-caption-text">The binary search algorithm divides the list in two equal sub-lists!</figcaption></figure>
<p>What will happen if we don&#8217;t use the constant ½, but another more accurate constant &#8220;C&#8221;, that can lead us closer to the searched item.</p>
<figure id="attachment_2579" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/InterpolationSearchfig.2.png"><img class="size-full wp-image-2579" title="Interpolation Search fig. 2" src="/wp-content/uploads/2012/01/InterpolationSearchfig.2.png" alt="Interpolation search" width="620" srcset="/wp-content/uploads/2012/01/InterpolationSearchfig.2.png 959w, /wp-content/uploads/2012/01/InterpolationSearchfig.2-300x80.png 300w" sizes="(max-width: 959px) 100vw, 959px" /></a><figcaption class="wp-caption-text">The interpolation search algorithm tries to improve the binary search!</figcaption></figure>
<p><span id="more-2560"></span></p>
<p>The question is how to find this value? Well, we know bounds of the interval and looking closer to the image above we can define the following formula.</p>
<pre lang="PHP">C = (x-L)/(R-L)</pre>
<p>Now we can be sure that we&#8217;re closer to the searched value.</p>
<h2>Implementation</h2>
<p>Here&#8217;s an implementation of interpolation search in PHP.</p>
<pre lang="PHP">$list = array(201, 209, 232, 233, 332, 399, 400);
$x = 332;

function interpolation_search($list, $x)
{
	$l = 0;
	$r = count($list) - 1;

	while ($l <= $r) {
		if ($list[$l] == $list[$r]) {
			if ($list[$l] == $x) {
				return $l;
			} else {
				// not found
				return -1;
			}
		}
		
		$k = ($x - $list[$l])/($list[$r] - $list[$l]);
		
		// not found
		if ($k < 0 || $k > 1) {
			return -1;
		}
		
		$mid = round($l + $k*($r - $l));
		
		if ($x < $list[$mid]) {
			$r = $mid - 1;
		} else if ($x > $list[$mid]) {
			$l = $mid + 1;
		} else {
			// success!
			return $mid;
		}
		
		// not found
		return -1;
	}
}

echo interpolation_search($list, $x);
</pre>
<h2>Complexity</h2>
<p>The complexity of this algorithm is log<sub>2</sub>(log<sub>2</sub>(n)) + 1. While I wont cover its proof, I’ll say that this is very slowly growing function as you can see on the following chart.</p>
<p><a href="/wp-content/uploads/2012/01/logntologlogn.png"><img class="alignnone size-full wp-image-2578" title="log(n) compared to log(log(n))" src="/wp-content/uploads/2012/01/logntologlogn.png" alt="log(n) compared to log(log(n))" width="600" height="371" srcset="/wp-content/uploads/2012/01/logntologlogn.png 600w, /wp-content/uploads/2012/01/logntologlogn-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a></p>
<p>Indeed when the values are equally dispersed into the interval this search algorithm can be extremely useful &#8211; way faster than the binary search. As you can see log<sub>2</sub>(log<sub>2</sub>(100 M)) ≈ 4.73 !!!</p>
<h2>Application</h2>
<p>As I said already this algorithm is extremely interesting and very appropriate in many use cases. Here’s an example where interpolation search can be used. Let’s say there’s an array with user data, sorted by their year of birth. We know in advance that all users are born in the 80’s. In this case sequential or even binary search can be slower than interpolation search.</p>
<pre lang="PHP">$list = array(
	0 => array('year' => 1980, 'name' => 'John Smith', 'username' => 'John'),
	1 => array('year' => 1980, ...),
	...
	10394 => array('year' => 1981, 'name' => 'Tomas M.', ...),
	...
	348489 => array('year' => '1985', 'name' => 'James Bond', ...),
	...
	2808008 => array('year' => '1990', 'name' => 'W.A. Mozart', ...)
);</pre>
<p>Now if we search for somebody born in 1981 a good approach is to use interpolation search.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </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>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/02/computer-algorithms-interpolation-search/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Jump Search</title>
		<link>/2011/12/12/computer-algorithms-jump-search/</link>
		<comments>/2011/12/12/computer-algorithms-jump-search/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 09:15:38 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Analysis of algorithms]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search algorithm]]></category>
		<category><![CDATA[Jump search]]></category>
		<category><![CDATA[jump search algorithm]]></category>
		<category><![CDATA[jumping forward]]></category>
		<category><![CDATA[Linear search]]></category>
		<category><![CDATA[primitive jump search]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[Selection algorithm]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[sequential search algorithm]]></category>
		<category><![CDATA[sorting algorithm]]></category>

		<guid isPermaLink="false">/?p=2521</guid>
		<description><![CDATA[Overview In my previous article I discussed how the sequential (linear) search can be used on an ordered lists, but then we were limited by the specific features of the given task. Obviously the sequential search on an ordered list is ineffective, because we consecutively check every one of its elements. Is there any way &#8230; <a href="/2011/12/12/computer-algorithms-jump-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Jump Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </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>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>In <a title="Computer Algorithms: Linear Search in Sorted Lists" href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/">my previous article</a> I discussed how the sequential (linear) search can be used on an ordered lists, but then we were limited by the specific features of the given task. Obviously the <a href="/2011/11/24/computer-algorithms-sequential-search/" title="Computer Algorithms: Sequential Search">sequential search</a> on an ordered list is ineffective, because we consecutively check every one of its elements. Is there any way we can optimize this approach? Well, because we know that the list is sorted we can check some of its items, but not all of them. Thus when an item is checked, if it is less than the desired value, we can skip some of the following items of the list by jumping ahead and then check again. Now if the checked element is greater than the desired value, we can be sure that the desired value is hiding somewhere between the previously checked element and the currently checked element. If not, again we can jump ahead. Of course a good approach is to use a fixed step. Let’s say the list length is n and the step’s length is k. Basically we check list(0), then list(k-1), list(2k-1) etc. Once we find the interval where the value might be (m*k-1 &lt; x &lt;= (m+1)*k &#8211; 1), we can perform a sequential search between the last two checked positions. By choosing this approach we avoid a lot the weaknesses of the sequential search algorithm. Many comparisons from the sequential search here are eliminated.</p>
<h2>How to choose the step&#8217;s length</h2>
<p>We know that it is a good practice to use a fixed size step. Actually when the step is 1, the algorithm is the traditional sequential search. The question is what should be the length of the step and is there any relation between the length of the list (n) and the length of the step (k)? Indeed there is such a relation and often you can see sources directly saying that the best length k = √n. Why is that?</p>
<p>Well, in the worst case, we do n/k jumps and if the last checked value is greater than the desired one, we do at most k-1 comparisons more. This means n/k + k &#8211; 1 comparisons. Now the question is for what values of k this function reaches its minimum. For those of you who remember maths classes this can be found with the formula -n/(k^2) + 1 = 0. Now it’s clear that for k = √n the minimum of the function is reached.</p>
<p>Of course you don’t need to prove this every time you use this algorithm. Instead you can directly assign √n to be the step length. However it is good to be familiar with this approach when trying to optimize an algorithm.</p>
<p>Let’s cosider the following list: (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610). Its length is 16. Jump search will find the value of 55 with the following steps.</p>
<figure id="attachment_2539" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/jump-search-fig-1.png"><img class="size-full wp-image-2539" title="jump-search-fig-1" src="/wp-content/uploads/2011/12/jump-search-fig-1.png" alt="Jump search basic implementation" width="620" srcset="/wp-content/uploads/2011/12/jump-search-fig-1.png 964w, /wp-content/uploads/2011/12/jump-search-fig-1-300x65.png 300w" sizes="(max-width: 964px) 100vw, 964px" /></a><figcaption class="wp-caption-text">Jump search skips some of the items of the list in order to improve performance!</figcaption></figure>
<h2>Implementation</h2>
<p>Let’s see an example of jump search, written in <a title="PHP on stoimen.com" href="/category/php/">PHP</a>.<span id="more-2521"></span></p>
<pre lang="PHP">
$list = array();

for ($i = 0; $i < 1000; $i++) {
	$list[] = $i;
}

// now we have a sorted list: (0, 1, 2, 3, ..., 999)

function jump_search($x, $list)
{
	// calculate the step
	$len = count($list);
	$step = floor(sqrt($len));
	$prev = 0;
	
	while ($list[($step < $len ? $step : $len)] < $x) {
		$prev = $step;
		$step += floor(sqrt($len));
		
		if ($step >= $len) {
			return FALSE;
		}
	}
	
	while ($list[$prev] < $x) {
		$prev++;
		if ($prev == ($step < $len ? $step : $len)) {
			return FALSE;
		}
	}
	
	if ($list[$prev] == $x) {
		return $prev;
	}
	
	return FALSE;
}

echo (int)jump_search(674, $list);
</pre>
<p>Here we have a sorted list with 1000 elements that looks like this: (0, 1, 2, ..., 999). Obviously with sequential search we'll find the value of 674 with exactly on the 674-th iteration. Here, with jump search we can reach it on the 44-th iteration, and this shows us the advantage of jump search over the sequential search on ordered lists.</p>
<h2>Further Optimization</h2>
<p>Although all examples here deal with small lists in practice this is not always true. Sometimes the step itself can be a very large number, so once you know the interval where the desired value could be you can perform jump search again.</p>
<p>We saw that the best size of the step is √n, but it is not a good idea to start from the first element of the list just as we didn’t in the example above. A better option is to begin from kth item. Now we can improve the above solution.</p>
<figure id="attachment_2542" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/jump-search-fig-2.png"><img class="size-full wp-image-2542" title="jump-search-fig-2" src="/wp-content/uploads/2011/12/jump-search-fig-2.png" alt="Basic jump search can be slightly optimized!" width="620" srcset="/wp-content/uploads/2011/12/jump-search-fig-2.png 964w, /wp-content/uploads/2011/12/jump-search-fig-2-300x65.png 300w" sizes="(max-width: 964px) 100vw, 964px" /></a><figcaption class="wp-caption-text">The basic implementation of jump search can be slightly optimized!</figcaption></figure>
<h2>Complexity</h2>
<p>Obviously the complexity of the algorithm is O(√n), but once we know the interval where the value is we can improve it by applying jump search again. Indeed let’s say the list length is 1,000,000. The jump interval should be: √1000000=1000. As you can see again, you can use jump search with a new step √1000≈31. Every time we find the desired interval we can apply the jump search algorithm with a smaller step. Of course finally the step will be 1. In this case the complexity of the algorithm is no longer O(√n). Now its complexity is approaching logarithmic value. The problem is that the implementation of this approach is considered to be more difficult than the binary search, where the complexity is also O(log(n)).</p>
<h2>Application</h2>
<p>As almost every algorithm the jump search is very convinient for a certain kind of tasks. Yes, the binary search is easy to implement and its complexity is O(log(n)), but in case of a very large list the direct jump to the middle can be a bad idea. Then we should make a large step back if the searched value is placed at the beginning of the list.</p>
<p>Perhaps every one of us has performed some sort of a primitive jump search in his life without even knowing it. Do you remember cassette recorders? We used the "fast forward" key and periodically checked whether the tape was on our favorite song. Once we stopped at the middle of the song we used the "rewind" button to find exactly the beginning of the song.</p>
<p>This clumsy example can give us the answer of where jump search can be better than binary search. The advantage of jump search is that you need to jump back only once (in case of the basic implementation).</p>
<figure id="attachment_2544" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/jump-search-fig-3.png"><img class="size-full wp-image-2544" title="jump-search-fig-3" src="/wp-content/uploads/2011/12/jump-search-fig-3.png" alt="Jump search is very useful when jumping back is significantly slower than jumping forward!" width="620" srcset="/wp-content/uploads/2011/12/jump-search-fig-3.png 964w, /wp-content/uploads/2011/12/jump-search-fig-3-300x65.png 300w" sizes="(max-width: 964px) 100vw, 964px" /></a><figcaption class="wp-caption-text">Jump search is very useful when jumping back is significantly slower than jumping forward!</figcaption></figure>
<p>If jumping back takes you significantly more time than jumping forward then you should use this algorithm.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </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>
<li><a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/12/12/computer-algorithms-jump-search/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort!</title>
		<link>/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/</link>
		<comments>/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 09:30:35 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[quicksort algorithm]]></category>
		<category><![CDATA[Selection algorithm]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[sorting algorithm]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Spreadsort]]></category>

		<guid isPermaLink="false">/?p=1689</guid>
		<description><![CDATA[Yes! It&#8217;s really really fast, and it&#8217;s far quicker than the quicksort algorithm, which is considered as the fastest sorting algorithm in practice. However how it&#8217;s possible to be faster than the quicksort, which is the fastest algorithm?! Is that true? Actually it&#8217;s true, but only in few cases. It works with integers, you&#8217;ve to &#8230; <a href="/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/" class="more-link">Continue reading <span class="screen-reader-text">Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort!</span> <span class="meta-nav">&#8594;</span></a><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/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
<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="/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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Yes! It&#8217;s really really fast, and it&#8217;s far quicker than the <a href="/2010/06/18/friday-algorithms-iterative-quicksort/">quicksort</a> algorithm, which is considered as the fastest sorting algorithm in practice. However how it&#8217;s possible to be faster than the quicksort, which is the fastest algorithm?! Is that true? Actually it&#8217;s true, but only in few cases. It works with integers, you&#8217;ve to know the first and the last element from that set and you&#8217;ve to be sure that every element is unique</p>
<p>Imagine you&#8217;ve a set of numbers all of them greater than 1 and lesser than 1000. Of course you&#8217;re not suppose to have all of the integers between 1 and 1000, but only few of them &#8211; think of 500 numbers between 1 and 1000! Here&#8217;s important to note &#8211; that this is only an example, you can have far more than only few numbers between 1 and 1000 &#8211; what about the numbers between 1 and 1,000,000 &#8211; this is a big set, isn&#8217;t it.</p>
<p>The question is &#8211; if there are so many constraints, why should I use that algorithm instead of quicksort, or another sorting algorithm, that works with everything. The answer is clear &#8211; yes, you&#8217;d prefer quicksort if you&#8217;ve to sort some arbitrary data, but when it comes to integers, and you&#8217;ve, let&#8217;s say, 1,000,000 integers, my advice is &#8211; use this algorithm!</p>
<h2>Sorting the Set</h2>
<h3>1. First Pass</h3>
<p>First we have an unsorted array, but we know the minimum and maximum of the set.</p>
<p><a href="/wp-content/uploads/2010/06/unsorted.png"><img class="aligncenter size-full wp-image-1701" title="unsorted" src="/wp-content/uploads/2010/06/unsorted.png" alt="an unsorted array of integers" width="283" height="111" /></a></p>
<p>On the first pass initialize an empty array with as many elements, as they are between the first and the last element of the set &#8211; for a set between 1 and 1000 &#8211; that will be an array with 1000 elements &#8211; each of which will be a zero in the beginning.</p>
<p><a href="/wp-content/uploads/2010/06/temp-array.png"><img class="aligncenter size-full wp-image-1700" title="temp-array" src="/wp-content/uploads/2010/06/temp-array.png" alt="temporary array with 0 on every element" width="277" height="138" /></a></p>
<p>Than loop trough the set and for every element in the set &#8211; you should put a 1 on it&#8217;s place</p>
<p><a href="/wp-content/uploads/2010/06/array-first-pass.png"><img class="aligncenter size-full wp-image-1699" title="array-first-pass" src="/wp-content/uploads/2010/06/array-first-pass.png" alt="sort a set - first pass" width="299" height="162" /></a></p>
<p>Now we have an array of 0 and 1.</p>
<h3>2. Second Pass</h3>
<p>After the first pass, you&#8217;d guess what you&#8217;ve to do &#8211; loop trough the second array and print the keys of the elements different from 0 &#8211; those that are 1.</p>
<p><a href="/wp-content/uploads/2010/06/sorted.png"><img class="aligncenter size-full wp-image-1698" title="sorted" src="/wp-content/uploads/2010/06/sorted.png" alt="a sorted set of integers" width="312" height="231" srcset="/wp-content/uploads/2010/06/sorted.png 312w, /wp-content/uploads/2010/06/sorted-300x222.png 300w" sizes="(max-width: 312px) 100vw, 312px" /></a></p>
<p>Now the array is sorted!</p>
<h2>Source Code</h2>
<pre lang="javascript">
var a = [34, 203, 3, 746, 200, 984, 198, 764];

function setSort(arr)
{
    var t = [], len = arr.length;
    for (var i = 0; i < 1000; i++) {
        t[i] = 0;
    }

    for (i = 0; i < len; i++) {
        t[arr[i]] = 1;
    }

    for (i = 0; i < 1000; i++) {
        if (1 == t[i]) {
            console.log(i);
        }
    }
}

setSort(a);
</pre>
<p>Now that you've seen that algorithm, perhaps you'd guess that it's no so difficult to change from integers to any other set, and once again I should say that in many cases this is the best algorithm for sorting! Very often quicksort is preferred, but not always there isn't something faster!</p>
<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/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
<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="/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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>
