<?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>Sort &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/sort/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Bucket Sort</title>
		<link>/2013/01/02/computer-algorithms-bucket-sort/</link>
		<comments>/2013/01/02/computer-algorithms-bucket-sort/#comments</comments>
		<pubDate>Wed, 02 Jan 2013 08:44:30 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[Bucket]]></category>
		<category><![CDATA[Bucket sort]]></category>
		<category><![CDATA[Combinatorics]]></category>
		<category><![CDATA[Counting sort]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[linear sorting algorithm]]></category>
		<category><![CDATA[linear time sorting algorithms]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Order theory]]></category>
		<category><![CDATA[Radix sort]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[two linear time sorting algorithms]]></category>

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

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

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

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

		<guid isPermaLink="false">/?p=3115</guid>
		<description><![CDATA[Finally the results from &#8220;You think you know algorithms&#8221; are out. This time only 3 of you have answered correctly to all the questions. 1. Which string searching algorithm is faster? Morris-Pratt correct answer (ref) Brute force Rabin-Karp 2. Can you use radix sort for sorting floats? Yes No correct answer (ref) 3. Quicksort needs &#8230; <a href="/2012/05/09/you-think-you-know-algorithms-quiz-results-2/" class="more-link">Continue reading <span class="screen-reader-text">You think you know algorithms. Quiz results!</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/02/29/you-think-you-know-algorithms-quiz-results/" rel="bookmark" title="You think you know algorithms. Quiz results!">You think you know algorithms. Quiz results! </a></li>
<li><a href="/2012/03/16/you-think-you-know-php-quiz-results/" rel="bookmark" title="You think you know PHP. Quiz Results!">You think you know PHP. Quiz Results! </a></li>
<li><a href="/2012/03/07/you-think-you-know-javascript-quiz-results/" rel="bookmark" title="You think you know javascript. Quiz results!">You think you know javascript. Quiz results! </a></li>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Finally the results from <a href="/2012/04/11/you-think-you-know-algorithms/" title="You think you know algorithms" target="_blank">&#8220;You think you know algorithms&#8221;</a> are out. This time only <strong>3</strong> of you have answered correctly to all the questions.</p>
<h3>1. Which string searching algorithm is faster?</h3>
<ul>
<li>Morris-Pratt <span style="color: #339966;">correct answer</span> (<a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" title="Computer Algorithms: Morris-Pratt String Searching" target="_blank">ref</a>)</li>
<li>Brute force</li>
<li>Rabin-Karp</li>
</ul>
<p><figure id="attachment_3123" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/Answers1.png"><img src="/wp-content/uploads/2012/05/Answers1.png" alt="Quiz results for &quot;Which string searching algorithm is faster?&quot;" title="Quiz results for &quot;Which string searching algorithm is faster?&quot;" width="600" height="371" class="size-full wp-image-3123" srcset="/wp-content/uploads/2012/05/Answers1.png 600w, /wp-content/uploads/2012/05/Answers1-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">  </figcaption></figure><br />
<span id="more-3115"></span></p>
<h3>2. Can you use radix sort for sorting floats?</h3>
<ul>
<li>Yes</li>
<li>No <span style="color: #339966;">correct answer</span> (<a href="/2012/03/19/computer-algorithms-radix-sort/" title="Computer Algorithms: Radix Sort" target="_blank">ref</a>)</li>
</ul>
<figure id="attachment_3124" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/Answers2.png"><img src="/wp-content/uploads/2012/05/Answers2.png" alt="Quiz results for &quot;Can you use radix sort for sorting floats?&quot;" title="Quiz results for &quot;Can you use radix sort for sorting floats?&quot;" width="600" height="371" class="size-full wp-image-3124" srcset="/wp-content/uploads/2012/05/Answers2.png 600w, /wp-content/uploads/2012/05/Answers2-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h3>3. Quicksort needs additional memory space?</h3>
<ul>
<li>Yes</li>
<li>No</li>
<li>Only in iterative implementation <span style="color: #339966;">correct answer</span> (<a href="/2012/03/13/computer-algorithms-quicksort/" title="Computer Algorithms: Quicksort" target="_blank">ref</a>)</li>
<li>Only in recursive implementation</li>
</ul>
<figure id="attachment_3125" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/Answers3.png"><img src="/wp-content/uploads/2012/05/Answers3.png" alt="Quiz results for &quot;Quicksort needs additional memory space?&quot;" title="Quiz results for &quot;Quicksort needs additional memory space?&quot;" width="600" height="371" class="size-full wp-image-3125" srcset="/wp-content/uploads/2012/05/Answers3.png 600w, /wp-content/uploads/2012/05/Answers3-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h3>4. In the worst case scenario which is slower?</h3>
<ul>
<li>Quicksort</li>
<li>Bubble sort</li>
<li>They are equally slow <span style="color: #339966;">correct answer</span> (<a href="/2012/03/13/computer-algorithms-quicksort/" title="Computer Algorithms: Quicksort" target="_blank">ref</a>)</li>
</ul>
<figure id="attachment_3126" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/Answers4.png"><img src="/wp-content/uploads/2012/05/Answers4.png" alt="Quiz results for &quot;In the worst case scenario which is slower?&quot;" title="Quiz results for &quot;In the worst case scenario which is slower?&quot;" width="600" height="371" class="size-full wp-image-3126" srcset="/wp-content/uploads/2012/05/Answers4.png 600w, /wp-content/uploads/2012/05/Answers4-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h3>5. Is merge sort faster than quicksort in general?</h3>
<ul>
<li>Yes, its complexity is O(n.log(n)) always!</li>
<li>No, in practice quicksort is often faster than merge sort <span style="color: #339966;">correct answer</span> (ref)<a href="/2012/03/13/computer-algorithms-quicksort/" title="Computer Algorithms: Quicksort" target="_blank"></a></li>
</ul>
<figure id="attachment_3127" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/Answers5.png"><img src="/wp-content/uploads/2012/05/Answers5.png" alt="Quiz results for &quot;Is merge sort faster than quicksort in general?&quot;" title="Quiz results for &quot;Is merge sort faster than quicksort in general?&quot;" width="600" height="371" class="size-full wp-image-3127" srcset="/wp-content/uploads/2012/05/Answers5.png 600w, /wp-content/uploads/2012/05/Answers5-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/02/29/you-think-you-know-algorithms-quiz-results/" rel="bookmark" title="You think you know algorithms. Quiz results!">You think you know algorithms. Quiz results! </a></li>
<li><a href="/2012/03/16/you-think-you-know-php-quiz-results/" rel="bookmark" title="You think you know PHP. Quiz Results!">You think you know PHP. Quiz Results! </a></li>
<li><a href="/2012/03/07/you-think-you-know-javascript-quiz-results/" rel="bookmark" title="You think you know javascript. Quiz results!">You think you know javascript. Quiz results! </a></li>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/05/09/you-think-you-know-algorithms-quiz-results-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Radix Sort</title>
		<link>/2012/03/19/computer-algorithms-radix-sort/</link>
		<comments>/2012/03/19/computer-algorithms-radix-sort/#comments</comments>
		<pubDate>Mon, 19 Mar 2012 20:54:00 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Best worst and average case]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[Bucket sort]]></category>
		<category><![CDATA[faster algorithm]]></category>
		<category><![CDATA[faster linear complexity algorithms]]></category>
		<category><![CDATA[Heapsort]]></category>
		<category><![CDATA[input algorithms]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[Introduction Algorithms]]></category>
		<category><![CDATA[linear complexity algorithms]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[purpose sorting algorithms]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Radix sort]]></category>
		<category><![CDATA[Shell sort]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>

		<guid isPermaLink="false">/?p=2922</guid>
		<description><![CDATA[Introduction Algorithms always depend on the input. We saw that general purpose sorting algorithms as insertion sort, bubble sort and quicksort can be very efficient in some cases and inefficient in other. Indeed insertion and bubble sort are considered slow, with best-case complexity of O(n2), but they are quite effective when the input is fairly &#8230; <a href="/2012/03/19/computer-algorithms-radix-sort/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Radix Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2013/01/02/computer-algorithms-bucket-sort/" rel="bookmark" title="Computer Algorithms: Bucket Sort">Computer Algorithms: Bucket Sort </a></li>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/03/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
<li><a href="/2012/03/20/algorithm-cheatsheet-radix-sort/" rel="bookmark" title="Algorithm Cheatsheet: Radix Sort">Algorithm Cheatsheet: Radix Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Algorithms always depend on the input. We saw that general purpose sorting algorithms as insertion sort, bubble sort and <a href="/2012/03/13/computer-algorithms-quicksort/" title="Computer Algorithms: Quicksort">quicksort</a> can be very efficient in some cases and inefficient in other. Indeed <a href="/2012/02/13/computer-algorithms-insertion-sort/" title="Computer Algorithms: Insertion Sort">insertion</a> and <a href="/2012/02/20/computer-algorithms-bubble-sort/" title="Computer Algorithms: Bubble Sort">bubble sort</a> are considered slow, with best-case complexity of O(n<sup>2</sup>), but they are quite effective when the input is fairly sorted. Thus when you have a sorted array and you add some “new” values to the array you can sort it quite effectively with insertion sort. On the other hand quicksort is considered one of the best general purpose sorting algorithms, but while it’s a great algorithm when the data is randomized it’s practically as slow as bubble sort when the input is almost or fully sorted. </p>
<p>Now we see that depending on the input algorithms may be effective or not. For almost sorted input insertion sort may be preferred instead of quicksort, which in general is a faster algorithm.</p>
<p>Just because the input is so important for an algorithm efficiency we may ask are there any sorting algorithms that are faster than O(n.log(n)), which is the average-case complexity for merge sort and quicksort. And the answer is yes there are faster, linear complexity algorithms, that can sort data faster than quicksort, merge sort and heapsort. But there are some constraints!</p>
<p>Everything sounds great but the thing is that we can’t sort any particular data with linear complexity, so the question is what rules the input must follow in order to be sorted in linear time.</p>
<p>Such an algorithm that is capable of sorting data in linear O(n) time is radix sort and the domain of the input is restricted &#8211; it must consist only of integers.</p>
<h2>Overview</h2>
<p>Let’s say we have an array of integers which is not sorted. Just because it consists only of integers and because array keys are integers in programming languages we can implement radix sort. </p>
<p>First for each value of the input array we put the value of “1” on the key-th place of the temporary array as explained on the following diagram.</p>
<p><figure id="attachment_2942" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/RadixSortBasicIdea.png"><img src="/wp-content/uploads/2012/03/RadixSortBasicIdea.png" alt="Radix sort first pass" title="Radix Sort Basic Idea" width="620" height="399" class="size-full wp-image-2942" srcset="/wp-content/uploads/2012/03/RadixSortBasicIdea.png 620w, /wp-content/uploads/2012/03/RadixSortBasicIdea-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Radix sort first pass</figcaption></figure><span id="more-2922"></span><br />
If there are repeating values in the input array we increment the corresponding value in the temporary array. After “initializing” the temporary array with one pass (with linear complexity) we can sort the input. </p>
<figure id="attachment_2941" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/RadixSortBasicIdea2ndpass.png"><img src="/wp-content/uploads/2012/03/RadixSortBasicIdea2ndpass.png" alt="Radix sort second pass" title="Radix Sort Basic Idea 2nd pass" width="620" height="392" class="size-full wp-image-2941" srcset="/wp-content/uploads/2012/03/RadixSortBasicIdea2ndpass.png 620w, /wp-content/uploads/2012/03/RadixSortBasicIdea2ndpass-300x189.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Radix sort second pass</figcaption></figure>
<h2>Implementation</h2>
<p>Implementing radix sort is very easy in fact, which is great. The thing is that old-school programming languages weren’t so flexible and we needed to initialize the entire temporary array. That leads to another problem &#8211; we must know the interval of values from the input. Fortunately nowadays programming languages and libraries are more flexible so we can initialize our temporary array even if we don’t know the interval of input values, as on the example bellow. PHP is somewhere in the middle &#8211; it&#8217;s flexible enough to build-up arrays in the memory without knowing their size in advance, but we still must ksort them. </p>
<pre lang="PHP">
$list = array(4, 3, 5, 9, 7, 2, 4, 1, 6, 5);
 
function radix_sort($input)
{
    $temp = $output = array();
	$len = count($input);
 
    for ($i = 0; $i < $len; $i++) {
		$temp[$input[$i]] = ($temp[$input[$i]] > 0) 
			? ++$temp[$input[$i]]
			: 1;
    }
    
    ksort($temp);
    
    foreach ($temp as $key => $val) {
		if ($val == 1) {
			$output[] = $key; 
		} else {
			while ($val--) {
				$output[] = $key;
			}
        }
    }
    
    return $output;
}
 
// 1, 2, 3, 4, 4, 5, 5, 6, 7, 9
print_r(radix_sort($list));
</pre>
<p>The problem is that PHP needs ksort &#8211; which is completely foolish as we&#8217;re trying to sort an array using &#8220;another&#8221; sorting method, but to overcome this you must know the interval of values in advance and initialize a temporary array with 0s, as on the example bellow.</p>
<pre lang="PHP">
define(MIN, 1);
define(MAX, 9);
$list = array(4, 3, 5, 9, 7, 2, 4, 1, 6, 5);

function radix_sort(&$input)
{
    $temp = array();
	$len = count($input);
 
	// initialize with 0s
    $temp = array_fill(MIN, MAX-MIN+1, 0);
    
    foreach ($input as $key => $val) {
    	$temp[$val]++;
    }
    
    $input = array();
    foreach ($temp as $key => $val) {
	if ($val == 1) {
		$input[] = $key;
	} else {
		while ($val--) {
			$input[] = $key;
		}
	}
    }
}

// 4, 3, 5, 9, 7, 2, 4, 1, 6, 5
var_dump($list);

radix_sort(&$list);

// 1, 2, 3, 4, 5, 5, 6, 7, 8, 9
var_dump($list);
</pre>
<p>Here the input is modified during the sorting process and it&#8217;s used as result.</p>
<h2>Complexity</h2>
<p>The complexity of radix sort is linear, which in terms of omega means O(n). That is a great benefit in performance compared to O(n.log(n)) or even worse with O(n<sup>2</sup>) as we can see on the following chart.</p>
<figure id="attachment_2940" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/RadixSortComplexity.png"><img src="/wp-content/uploads/2012/03/RadixSortComplexity.png" alt="Linear function compared to n.log(n) and n^2" title="Radix Sort Complexity" width="600" height="371" class="size-full wp-image-2940" srcset="/wp-content/uploads/2012/03/RadixSortComplexity.png 600w, /wp-content/uploads/2012/03/RadixSortComplexity-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">Linear function compared to n.log(n) and n^2</figcaption></figure>
<h2>Why using radix sort</h2>
<h3>1. It’s fast</h3>
<p>Radix sort is very fast compared to other sorting algorithms as we saw on the diagram above. This algorithm is very useful in practice because in practice we often sort sets of integers.</p>
<figure id="attachment_2939" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/Prosofradixsort.png"><img src="/wp-content/uploads/2012/03/Prosofradixsort.png" alt="Pros of radix sort" title="Pros of radix sort" width="620" height="399" class="size-full wp-image-2939" srcset="/wp-content/uploads/2012/03/Prosofradixsort.png 620w, /wp-content/uploads/2012/03/Prosofradixsort-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h3>2. It’s easy to understand and implement</h3>
<p>Even a beginner can understand and implement radix sort, which is great. You need no more than few loops to implement it.</p>
<h2>Why NOT using radix sort</h2>
<h3>1. Works only with integers</h3>
<p>If you’re not sure about the input better do not use radix sort. We may think that our input consists only of integers and we can go for radix sort, but what if in the future someone passes floats or strings to our routine.</p>
<figure id="attachment_2938" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/Consofradixsort.png"><img src="/wp-content/uploads/2012/03/Consofradixsort.png" alt="Cons of radix sort" title="Cons of radix sort" width="621" height="407" class="size-full wp-image-2938" srcset="/wp-content/uploads/2012/03/Consofradixsort.png 621w, /wp-content/uploads/2012/03/Consofradixsort-300x196.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h3>2. Requires additional space</h3>
<p>Radix sort needs additional space &#8211; at least as much as the input.</p>
<h2>Final Words</h2>
<p>Radix sort is restricted by the input’s domain, but I must say that in practice there are tons of cases where only integers are sorted. This is when we get some data from the db based on primary keys &#8211; typically primary in database tables are integers as well. So practically there are lots of cases of sorting integers, so radix sort may be one very, very useful algorithm and it is so cool that it is also easy to implement.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2013/01/02/computer-algorithms-bucket-sort/" rel="bookmark" title="Computer Algorithms: Bucket Sort">Computer Algorithms: Bucket Sort </a></li>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/03/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
<li><a href="/2012/03/20/algorithm-cheatsheet-radix-sort/" rel="bookmark" title="Algorithm Cheatsheet: Radix Sort">Algorithm Cheatsheet: Radix Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/03/19/computer-algorithms-radix-sort/feed/</wfw:commentRss>
		<slash:comments>7</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>Algorithm cheatsheet: Quicksort</title>
		<link>/2012/03/12/algorithm-cheatsheet-quicksort/</link>
		<comments>/2012/03/12/algorithm-cheatsheet-quicksort/#comments</comments>
		<pubDate>Mon, 12 Mar 2012 14:49:37 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[cheatsheets]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[algorithm cheat sheet]]></category>
		<category><![CDATA[algorithm pseudo code]]></category>
		<category><![CDATA[Cheat sheet]]></category>
		<category><![CDATA[cheatsheet]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[pdf]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>

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

Related posts:<ol>
<li><a href="/2010/06/11/friday-algorithms-quicksort-difference-between-php-and-javascript/" rel="bookmark" title="Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript">Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2012/03/20/algorithm-cheatsheet-radix-sort/" rel="bookmark" title="Algorithm Cheatsheet: Radix Sort">Algorithm Cheatsheet: Radix Sort </a></li>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Click on the image to download this cheatsheet on PDF!</p>
<figure id="attachment_2901" style="width: 534px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/QuicksortCheatsheet.pdf"><img src="/wp-content/uploads/2012/03/QuicksortCheatsheet.png" alt="" title="Quicksort Cheatsheet" width="534" height="2000" class="size-full wp-image-2901" srcset="/wp-content/uploads/2012/03/QuicksortCheatsheet.png 534w, /wp-content/uploads/2012/03/QuicksortCheatsheet-80x300.png 80w" sizes="(max-width: 534px) 100vw, 534px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/06/11/friday-algorithms-quicksort-difference-between-php-and-javascript/" rel="bookmark" title="Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript">Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2012/03/20/algorithm-cheatsheet-radix-sort/" rel="bookmark" title="Algorithm Cheatsheet: Radix Sort">Algorithm Cheatsheet: Radix Sort </a></li>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/03/12/algorithm-cheatsheet-quicksort/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Bubble Sort</title>
		<link>/2012/02/20/computer-algorithms-bubble-sort/</link>
		<comments>/2012/02/20/computer-algorithms-bubble-sort/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 13:33:08 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[Discrete mathematics]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[famous sorting algorithm]]></category>
		<category><![CDATA[Heapsort]]></category>
		<category><![CDATA[ineffective algorithm]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[Order theory]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Selection sort]]></category>
		<category><![CDATA[slow ineffective algorithm]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[well known sorting algorithm]]></category>

		<guid isPermaLink="false">/?p=2729</guid>
		<description><![CDATA[Overview It&#8217;s weird that bubble sort is the most famous sorting algorithm in practice since it is one of the worst approaches for data sorting. Why is bubble sort so famous? Perhaps because of its exotic name or because it is so easy to implement. First let&#8217;s take a look on its nature. Bubble sort &#8230; <a href="/2012/02/20/computer-algorithms-bubble-sort/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Bubble Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/07/09/friday-algorithms-javascript-bubble-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Bubble Sort">Friday Algorithms: JavaScript Bubble Sort </a></li>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/02/13/computer-algorithms-insertion-sort/" rel="bookmark" title="Computer Algorithms: Insertion Sort">Computer Algorithms: Insertion Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>It&#8217;s weird that bubble sort is the most famous sorting algorithm in practice since it is one of the worst approaches for data sorting. Why is bubble sort so famous? Perhaps because of its exotic name or because it is so easy to implement. First let&#8217;s take a look on its nature.</p>
<p>Bubble sort consists of comparing each pair of adjacent items. Then one of those two items is considered smaller (lighter) and if the lighter element is on the right side of its neighbour, they swap places. Thus the lightest element bubbles to the surface and at the end of each iteration it appears on the top. I&#8217;ll try to explain this simple principle with some pictures.</p>
<h3>1. Each two adjacent elements are compared</h3>
<figure id="attachment_2736" style="width: 962px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStep1CompareTwoElements1.png"><img src="/wp-content/uploads/2012/02/BubbleSortStep1CompareTwoElements1.png" alt="In bubble sort we've to compare each two adjacent elements" title="BubbleSortStep1CompareTwoElements" width="962" height="250" class="size-full wp-image-2736" srcset="/wp-content/uploads/2012/02/BubbleSortStep1CompareTwoElements1.png 962w, /wp-content/uploads/2012/02/BubbleSortStep1CompareTwoElements1-300x77.png 300w" sizes="(max-width: 962px) 100vw, 962px" /></a><figcaption class="wp-caption-text">In bubble sort we've to compare each two adjacent elements</figcaption></figure>
<p>Here &#8220;2&#8221; appears to be less than &#8220;4&#8221;, so it is considered lighter and it continues to bubble to the surface (the front of the array).<br />
<span id="more-2729"></span></p>
<h3>2. Swap with heavier elements</h3>
<figure id="attachment_2738" style="width: 962px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStep2AnElementStartstoBubble.png"><img src="/wp-content/uploads/2012/02/BubbleSortStep2AnElementStartstoBubble.png" alt="If heavier elements appear on the way we should swap them" title="BubbleSortStep2AnElementStartstoBubble" width="962" height="241" class="size-full wp-image-2738" srcset="/wp-content/uploads/2012/02/BubbleSortStep2AnElementStartstoBubble.png 962w, /wp-content/uploads/2012/02/BubbleSortStep2AnElementStartstoBubble-300x75.png 300w" sizes="(max-width: 962px) 100vw, 962px" /></a><figcaption class="wp-caption-text">If heavier elements appear on the way we should swap them</figcaption></figure>
<p>On his way to the surface the currently lightest item meets a heavier element. Then they swap places.</p>
<h3>3. Move forward and swap with each heavier item</h3>
<figure id="attachment_2740" style="width: 963px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStep3ALighterElementStartstoBubble.png"><img src="/wp-content/uploads/2012/02/BubbleSortStep3ALighterElementStartstoBubble.png" alt="Swapping is slow and that is the main reason not to use bubble sort" title="BubbleSortStep3ALighterElementStartstoBubble" width="963" height="377" class="size-full wp-image-2740" srcset="/wp-content/uploads/2012/02/BubbleSortStep3ALighterElementStartstoBubble.png 963w, /wp-content/uploads/2012/02/BubbleSortStep3ALighterElementStartstoBubble-300x117.png 300w" sizes="(max-width: 963px) 100vw, 963px" /></a><figcaption class="wp-caption-text">Swapping is slow and that is the main reason not to use bubble sort</figcaption></figure>
<p>The problem with bubble sort is that you may have to swap a lot of elements.</p>
<h3>4. If there is a lighter element, then this item begins to bubble to the surface</h3>
<figure id="attachment_2741" style="width: 959px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStep4ALighterElementStartstoBubble.png"><img src="/wp-content/uploads/2012/02/BubbleSortStep4ALighterElementStartstoBubble.png" alt="We can be sure that on each step the algorithm bubbles the lightest element so far" title="BubbleSortStep4ALighterElementStartstoBubble" width="959" height="180" class="size-full wp-image-2741" srcset="/wp-content/uploads/2012/02/BubbleSortStep4ALighterElementStartstoBubble.png 959w, /wp-content/uploads/2012/02/BubbleSortStep4ALighterElementStartstoBubble-300x56.png 300w" sizes="(max-width: 959px) 100vw, 959px" /></a><figcaption class="wp-caption-text">We can be sure that on each step the algorithm bubbles the lightest element so far</figcaption></figure>
<p>If the currently lightest element meets another item that is lighter, then the newest currently lightest element starts to bubble to the top.</p>
<h3>5. Finally the lightest element is on its place</h3>
<figure id="attachment_2742" style="width: 959px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStep5Themostlightelementisonitsplace.png"><img src="/wp-content/uploads/2012/02/BubbleSortStep5Themostlightelementisonitsplace.png" alt="Finally the list begins to look sorted" title="BubbleSortStep5Themostlightelementisonitsplace" width="959" height="180" class="size-full wp-image-2742" srcset="/wp-content/uploads/2012/02/BubbleSortStep5Themostlightelementisonitsplace.png 959w, /wp-content/uploads/2012/02/BubbleSortStep5Themostlightelementisonitsplace-300x56.png 300w" sizes="(max-width: 959px) 100vw, 959px" /></a><figcaption class="wp-caption-text">Finally the list begins to look sorted</figcaption></figure>
<p>At the end of each iteration we can be sure that the lightest element is on the right place &#8211; at the beginning of the list.</p>
<p>The problem is that this algorithm needs a tremendous number of comaprisons and as we know already this can be slow.</p>
<p><iframe src="https://docs.google.com/present/embed?id=dc7ft52d_9cgbm35fh&#038;autoStart=true&#038;loop=true&#038;size=m" frameborder="0" width="525" height="420"></iframe></p>
<p>We can easily see how ineffective bubble sort is. Now the question remains &#8211; why is it so famous? Maybe indeed the answer lies in the simplicity of its implementation. Let&#8217;s see how to implement bubble sort.</p>
<h2>Implementation</h2>
<p>Implementing bubble sort is easy. The question is how easy? Well, obviously after understanding the principles of this algorithm every developer, even a beginner, can implement it. Here&#8217;s a PHP implementation of bubble sort.</p>
<pre lang="PHP">
$input = array(6, 5, 3, 1, 8, 7, 2, 4);

function bubble_sort($arr)
{
	$length = count($arr);
	
	for ($i = 0; $i < $length; $i++) {
		for ($j = $length-1; $j > $i; $j--) {
			if ($arr[$j] < $arr[$j-1]) {
				$t = $arr[$j];
				$arr[$j] = $arr[$j-1];
				$arr[$j-1] = $t;
			}
		}
	}
	
	return $arr;
}

// 1, 2, 3, 4, 5, 6, 7, 8
$output = bubble_sort($input);
</pre>
<p>Clearly the implementation consists of few lines of code and two nested loops.</p>
<h2>Complexity: Where's Bubble Sort Compared to Other Sorting Algorithms</h2>
<p>Compared to other sorting algorithm, bubble sort is really slow. Indeed the complexity of this algoritm is O(n<sup>2</sup>) which can't be worse. It's weird that the most well known sorting algorithm is the slowest one.</p>
<figure id="attachment_2758" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortComparedToOthers.png"><img src="/wp-content/uploads/2012/02/BubbleSortComparedToOthers.png" alt="Bubble sort compared to quicksort, merge sort and heapsort in the average case" title="BubbleSortComparedToOthers" width="600" height="371" class="size-full wp-image-2758" srcset="/wp-content/uploads/2012/02/BubbleSortComparedToOthers.png 600w, /wp-content/uploads/2012/02/BubbleSortComparedToOthers-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">Bubble sort compared to quicksort, merge sort and heapsort in the average case</figcaption></figure>
<p>Even for small values of n, the number of comparisons and swaps can be tremendous.</p>
<figure id="attachment_2751" style="width: 1082px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/BubbleSortStats-2.png"><img src="/wp-content/uploads/2012/02/BubbleSortStats-2.png" alt="stats" title="Bubble sort is three times slower than quicksort even for n = 100, but it's easier to impelemnt" width="1082" height="654" class="size-full wp-image-2751" srcset="/wp-content/uploads/2012/02/BubbleSortStats-2.png 1082w, /wp-content/uploads/2012/02/BubbleSortStats-2-300x181.png 300w, /wp-content/uploads/2012/02/BubbleSortStats-2-1024x618.png 1024w" sizes="(max-width: 1082px) 100vw, 1082px" /></a><figcaption class="wp-caption-text">Bubble sort is three times slower than quicksort even for n = 100, but it's easier to impelemnt</figcaption></figure>
<p>Another problem is that most of the languages (libraries) have built-in sorting functions, that they don't make use of bubble sort and are faster for sure. So why a developer should implement bubble sort at all?</p>
<h2>Application: 3 Cool Reasons To Use Bubble Sort</h2>
<p>We saw that bubble sort is slow and ineffective, yet it is used in practice. Why? Is there any reason to use this slow, ineffective algorithm with weird name? Yes and here are some of them that might be helpful for any developer.</p>
<h3>1. It is easy to implement</h3>
<p>Definitely bubble sort is easier to implement than other "complex" sorting algorithms as quicksort. Bubble sort is easy to remember and easy to code and that's great instead of learning and remembering tons of code.</p>
<h3>2. Because the library can't help</h3>
<p>Let's say you work with JavaScript. Great, there you get array.sort() which can help for this: [3, 1, 2].sort(). But what would happen if you'd rather like to sort more "complex" structures like ... some DOM nodes. Here we have three LI nodes and we want to sort them in some order. Obviously you can't compare them with the "<" operator, so we've to come up with some custom solution.



<pre lang="html4strict">
<a href="#">Click here to sort the list</a>

<li>node 3</li>
<li>node 1</li>
<li>node 2</li>
</pre>
<p>Here sort() can&#8217;t help us and we&#8217;ve to code our own function. However we have only few elements (three in our case). Why not using bubble sort?</p>
<h3>3. The list is almost sorted</h3>
<p>One of the problems with bubble sort is that it consists of too much swapping, but what if we know that the list is almost sorted?  </p>
<pre lang="javascript">
// almost sorted
[1, 2, 4, 3, 5]
</pre>
<p>We have to swap only 3 with 4. </p>
<p>Note that in the best case bubble sort&#8217;s complexity is O(n) &#8211; faster than quicksort&#8217;s best case!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/07/09/friday-algorithms-javascript-bubble-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Bubble Sort">Friday Algorithms: JavaScript Bubble Sort </a></li>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/02/13/computer-algorithms-insertion-sort/" rel="bookmark" title="Computer Algorithms: Insertion Sort">Computer Algorithms: Insertion Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/02/20/computer-algorithms-bubble-sort/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Insertion Sort</title>
		<link>/2012/02/13/computer-algorithms-insertion-sort/</link>
		<comments>/2012/02/13/computer-algorithms-insertion-sort/#comments</comments>
		<pubDate>Mon, 13 Feb 2012 14:21:57 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Application This algorithm]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[Linear search]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[player]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Selection sort]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Strand sort]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[therefore sorting algorithms]]></category>
		<category><![CDATA[typical algorithm]]></category>

		<guid isPermaLink="false">/?p=2711</guid>
		<description><![CDATA[Overview Sorted data can dramatically change the speed of our program, therefore sorting algorithms are something quite special in computer science. For instance searching in a sorted list is faster than searching in an unordered list. There are two main approaches in sorting &#8211; by comparing the elements and without comparing them. A typical algorithm &#8230; <a href="/2012/02/13/computer-algorithms-insertion-sort/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Insertion Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/03/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2012/02/20/computer-algorithms-bubble-sort/" rel="bookmark" title="Computer Algorithms: Bubble Sort">Computer Algorithms: Bubble Sort </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>Sorted data can dramatically change the speed of our program, therefore sorting algorithms are something quite special in computer science. For instance searching in a sorted list is faster than searching in an unordered list.</p>
<p>There are two main approaches in sorting &#8211; by comparing the elements and without comparing them. A typical algorithm from the first group is insertion sort. This algorithm is very simple and very intuitive to implement, but unfortunately it is not so effective compared to other sorting algorithms as <a href="/2010/06/18/friday-algorithms-iterative-quicksort/" title="Friday Algorithms: Iterative Quicksort">quicksort</a> and merge sort. Indeed insertion sort is useful for small sets of data with no more than about 20 items.</p>
<p>Insertion sort it is very intuitive method of sorting items and we often use it when we play card games. In this case the player often gets an unordered set of playing cards and intuitively starts to sort it. First by taking a card, making some comparisons and then putting the card on the right position.</p>
<p>So let’s say we have an array of data. In the first step the array is unordered, but we can say that it consists of two sub-sets: sorted and unordered, where on the first step the only item in the sorted sub-set is its first item. If the length of the array is n the algorithm is considered completed in n-1 steps. On each step our sorted subset is growing with one item. The thing is that we take the first item from the unordered sub-set and with some comparisons we put it into its place in the sorted sub-set, like on the diagram bellow.</p>
<p><figure id="attachment_2719" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/InsertionSortPrinciple.png"><img src="/wp-content/uploads/2012/02/InsertionSortPrinciple.png" alt="Main principle of insertion sort" title="Principle of Insertion Sort" width="620" class="size-full wp-image-2719" srcset="/wp-content/uploads/2012/02/InsertionSortPrinciple.png 960w, /wp-content/uploads/2012/02/InsertionSortPrinciple-300x107.png 300w" sizes="(max-width: 960px) 100vw, 960px" /></a><figcaption class="wp-caption-text">Main principle of insertion sort.</figcaption></figure><br />
<span id="more-2711"></span><br />
The insertion itself is the tricky part. We can insert the item once we find an item with a smaller value or if we have reached the front of the array like on the diagram bellow.</p>
<figure id="attachment_2721" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/InsertionSort.png"><img src="/wp-content/uploads/2012/02/InsertionSort.png" alt="Insertion sort example" title="Insertion Sort" width="620" class="size-full wp-image-2721" srcset="/wp-content/uploads/2012/02/InsertionSort.png 727w, /wp-content/uploads/2012/02/InsertionSort-300x196.png 300w" sizes="(max-width: 727px) 100vw, 727px" /></a><figcaption class="wp-caption-text">Example of insertion sort</figcaption></figure>
<h2>Implementation</h2>
<p>Here’s a quick implementation of insertion sort in PHP. The good thing is that it is easy to implement, but there are bad news too &#8211; insertion sort is slow and it is ineffective for large data sets.</p>
<pre lang="PHP">
$data = array(4, 2, 4, 1, 2, 6, 8, 19, 3);

function insertion_sort(&$arr)
{
	$len = count($arr);
	
	for ($i = 1; $i < $len; $i++) {
		$tmp = $arr[$i];
		$j = $i;
		
		while (($j >= 0) && ($arr[$j-1] > $tmp)) {
			$arr[$j] = $arr[$j-1];
			$j--;
		}
		$arr[$j] = $tmp;
	}
}
</pre>
<p>We can improve this code a little by using a sentinel, just like the sequential search, in order to remove one of the comparisons.</p>
<pre lang="PHP">
$data = array(4, 2, 4, 1, 2, 6, 8, 19, 3);

function insertion_sort_sentinel(&$arr)
{
	$len = count($arr);
	array_unshift(&$arr, -1);
	
	for ($i = 1; $i < $len+1; $i++) {
		$tmp = $arr[$i];
		$j = $i;
		
		while ($arr[$j-1] > $tmp) {
			$arr[$j] = $arr[$j-1];
			$j--;
		}
		$arr[$j] = $tmp;
	}
	array_shift(&$arr); // remove the sentinel
}
</pre>
<p>Just because we use searching the right position in an ordered array we can use binary search in order to improve even more the algorithm above. Unfortunately this doesn’t improve so much the general efficiency of this algorithm.</p>
<h2>Complexity</h2>
<p>As I said this algorithm is not so effective. Its complexity is O(n<sup>2</sup>) which is far worse than the O(n*log(n)) of quicksort, as you can see on the diagram bellow. </p>
<figure id="attachment_2723" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/InsertionSortComplexityChart.png"><img src="/wp-content/uploads/2012/02/InsertionSortComplexityChart.png" alt="n*n vs. n*log(n)" title="Insertion Sort Complexity Chart" width="600" height="371" class="size-full wp-image-2723" srcset="/wp-content/uploads/2012/02/InsertionSortComplexityChart.png 600w, /wp-content/uploads/2012/02/InsertionSortComplexityChart-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">n*n vs. n*log(n)</figcaption></figure>
<h2>Application</h2>
<p>This algorithm is useful for small sets of data and even if it doesn&#8217;t look like the most effective sorting algorithm, insertion sort can be useful for some reasons. First of all it is easy to implement, but it also does not require additional memory and it can be fast if the data is almost nearly sorted, which is great.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/02/27/computer-algorithms-shell-sort/" rel="bookmark" title="Computer Algorithms: Shell Sort">Computer Algorithms: Shell Sort </a></li>
<li><a href="/2012/03/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2012/02/20/computer-algorithms-bubble-sort/" rel="bookmark" title="Computer Algorithms: Bubble Sort">Computer Algorithms: Bubble Sort </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/02/13/computer-algorithms-insertion-sort/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>
