<?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>Spreadsort &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/spreadsort/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>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>
