<?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>Insertion sort &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/insertion-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: 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>Computer Algorithms: Merge Sort</title>
		<link>/2012/03/05/computer-algorithms-merge-sort/</link>
		<comments>/2012/03/05/computer-algorithms-merge-sort/#comments</comments>
		<pubDate>Mon, 05 Mar 2012 20:50:55 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Adaptive sort]]></category>
		<category><![CDATA[Best worst and average case]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[comparison model sorting algorithm]]></category>
		<category><![CDATA[Divide and conquer algorithm]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[interative solution]]></category>
		<category><![CDATA[interative solutions]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[recursive solution]]></category>
		<category><![CDATA[Shell sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Strand sort]]></category>
		<category><![CDATA[three algorithms]]></category>
		<category><![CDATA[USD]]></category>

		<guid isPermaLink="false">/?p=2847</guid>
		<description><![CDATA[Introduction Basically sorting algorithms can be divided into two main groups. Such based on comparisons and such that are not. I already posted about some of the algorithms of the first group. Insertion sort, bubble sort and Shell sort are based on the comparison model. The problem with these three algorithms is that their complexity &#8230; <a href="/2012/03/05/computer-algorithms-merge-sort/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Merge Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
<li><a href="/2010/07/02/friday-algorithms-javascript-merge-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Merge Sort">Friday Algorithms: JavaScript Merge 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/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>Introduction</h2>
<p>Basically sorting algorithms can be divided into two main groups. Such based on comparisons and such that are not. I already posted about some of the algorithms of the first group. Insertion sort, bubble sort and Shell sort are based on the comparison model. The problem with these three algorithms is that their complexity is O(n<sup>2</sup>) so they are very slow. </p>
<p>So is it possible to sort a list of items by comparing their items faster than O(n<sup>2</sup>)? The answer is yes and here’s how we can do it.</p>
<p>The nature of those three algorithms mentioned above is that we almost compared each two items from initial list.</p>
<figure id="attachment_2860" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/Principlesofprimitivesortingalgorithms.png"><img src="/wp-content/uploads/2012/03/Principlesofprimitivesortingalgorithms.png" alt="Insertion sort and bubble sort make too many comparisons, exactly what merge sort tries to overcome!" title="Principles of primitive sorting algorithms" width="620" class="size-full wp-image-2860" srcset="/wp-content/uploads/2012/03/Principlesofprimitivesortingalgorithms.png 640w, /wp-content/uploads/2012/03/Principlesofprimitivesortingalgorithms-300x89.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">Insertion sort and bubble sort make too many comparisons, exactly what merge sort tries to overcome!</figcaption></figure>
<p>This, of course, is not the best approach and we don’t need to do that. Instead we can try to divide the list into smaller lists and then sort them. After sorting the smaller lists, which is supposed to be easier than sorting the entire initial list, we can try to merge the result into one sorted list. This technique is typically known as “divide and conquer”.</p>
<p>Normally if a problem is too difficult to solve, we can try to break it apart into smaller sub-sets of this problem and try to solve them. Then somehow we can merge the results of the solved problems. </p>
<p><figure id="attachment_2856" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/Divideandconquer.png"><img src="/wp-content/uploads/2012/03/Divideandconquer.png" alt="If it&#039;s too difficult to sort a large list of items, we can break it apart into smaller sub-lists and try to sort them!" title="Divide and conquer" width="620" class="size-full wp-image-2856" srcset="/wp-content/uploads/2012/03/Divideandconquer.png 640w, /wp-content/uploads/2012/03/Divideandconquer-300x188.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">If it&#039;s too difficult to sort a large list of items, we can break it apart into smaller sub-lists and try to sort them!</figcaption></figure><br />
<span id="more-2847"></span></p>
<h2>Overview</h2>
<p>Merge sort is a comparison model sorting algorithm based on the “divide and conquer” principle. So far so good, so let’s say we have a very large list of data, which we want to sort. Obviously it will be better if we divide the list into two sub-lists with equal length and then sort them. If they remain too large, we can continue breaking them down until we get to something very easy to sort as shown on the diagram bellow.</p>
<figure id="attachment_2859" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/Mergepartinmergesort.png"><img src="/wp-content/uploads/2012/03/Mergepartinmergesort.png" alt="Merge sort is a typical example of divide and conquer technique!" title="Merge part in merge sort" width="620" class="size-full wp-image-2859" srcset="/wp-content/uploads/2012/03/Mergepartinmergesort.png 624w, /wp-content/uploads/2012/03/Mergepartinmergesort-232x300.png 232w" sizes="(max-width: 624px) 100vw, 624px" /></a><figcaption class="wp-caption-text">Merge sort is a typical example of divide and conquer technique!</figcaption></figure>
<p>The thing is that on some step of the algorithm we have two sorted lists and the tricky part is to merge them. However this is not so difficult.<br />
We can start comparing the first items of the lists and than we can pop the smaller of them both and put it into a new list containing the merged (sorted) array.</p>
<h2>Implementation</h2>
<p>The good news is that this algorithm is fast, but not so difficult to implement and that sounds quite good from a developer’s point of view. Here’s the implementation in PHP. Note that every algorithm that follows the divide and conquer principles can be easily implemented in a recursive solution. However recursion can be bitter so you can go for a iterative solution. Typically recursion is &#8220;replaced&#8221; by additional memory space in iterative solutions. Here&#8217;s a recursive version of merge sort.</p>
<pre lang="PHP">
$input = array(6, 5, 3, 1, 8, 7, 2, 4);

function merge_sort($arr)  
{  
	if (count($arr) <= 1) {
		return $arr;  
	}

	$left = array_slice($arr, 0, (int)(count($arr)/2));  
	$right = array_slice($arr, (int)(count($arr)/2));  
	
	$left = merge_sort($left);  
	$right = merge_sort($right);  
	
	$output = merge($left, $right);  

	return $output;  
}  
      
      
function merge($left, $right)  
{  
	$result = array();  

	while (count($left) > 0 && count($right) > 0) {  
		if ($left[0] <= $right[0]) {  
			array_push($result, array_shift($left));  
		} else {  
			array_push($result, array_shift($right));  
		}  
	}  
      
	array_splice($result, count($result), 0, $left);  
	array_splice($result, count($result), 0, $right);  

	return $result;  
}  

// 1, 2, 3, 4, 5, 6, 7, 8
$output = merge_sort($input);
</pre>
<h2>Complexity</h2>
<p>It’s great that the complexity of merge sort is O(n*log(n)) even in the worst case! Note that even quicksort’s complexity can be O(n<sup>2</sup>) in the worst case. So we can be sure that merge sort is very stable no matter the input.</p>
<figure id="attachment_2857" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/mergesortcomplexity.png"><img src="/wp-content/uploads/2012/03/mergesortcomplexity.png" alt="Merge sort complexity is O(n*log(n))" title="merge sort complexity" width="620" class="size-full wp-image-2857" srcset="/wp-content/uploads/2012/03/mergesortcomplexity.png 640w, /wp-content/uploads/2012/03/mergesortcomplexity-300x185.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">Merge sort complexity is O(n*log(n))</figcaption></figure>
<figure id="attachment_2858" style="width: 481px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/SortingAlgorithmsComplexity.jpg"><img src="/wp-content/uploads/2012/03/SortingAlgorithmsComplexity.jpg" alt="Merge sort complexity is O(n*log(n)) even in the worst case!" title="Sorting Algorithms Complexity" width="481" height="104" class="size-full wp-image-2858" srcset="/wp-content/uploads/2012/03/SortingAlgorithmsComplexity.jpg 481w, /wp-content/uploads/2012/03/SortingAlgorithmsComplexity-300x64.jpg 300w" sizes="(max-width: 481px) 100vw, 481px" /></a><figcaption class="wp-caption-text">Merge sort complexity is O(n*log(n)) even in the worst case!</figcaption></figure>
<h2>Two reasons why merge sort is useful</h2>
<h3>1. Fast no matter the input</h3>
<p>Merge sort is a great sorting algorithm mainly because it’s very fast and stable. It’s complexity is the same even in the worst case and it is O(n*log(n)). Note that even quicksort's complexity is O(n<sup>2</sup>) in the worst case, which for n = 20 is about 4.6 times slower!</p>
<figure id="attachment_2861" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/03/mergesortvs.bubblesortforn20.png"><img src="/wp-content/uploads/2012/03/mergesortvs.bubblesortforn20.png" alt="Merge sort is about 4.6 times faster than quicksort for n = 20!" title="mergesort vs. bubble sort for n = 20" width="620" class="size-full wp-image-2861" srcset="/wp-content/uploads/2012/03/mergesortvs.bubblesortforn20.png 640w, /wp-content/uploads/2012/03/mergesortvs.bubblesortforn20-300x120.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h3>2. Easy implementation</h3>
<p>Another cool reason is that merge sort is easy to implement. Indeed most of the developer consider something fast to be difficult to implement, but that's not the case of merge sort.</p>
<h2>Three reasons why merge sort is not useful</h2>
<h3>1. Slower than non-comparison based algorithms</h3>
<p>Merge sort is however based on the comparison model and as such can be slower than algorithms non-based on comparisons that can sort data in linear time. Of course, this depends on the input data, so we must be careful for the input.</p>
<h3>2. Difficult to implement for beginners</h3>
<p>Although I don’t think this can be the main reason why not to use merge sort some people say that it can be difficult to implement for beginners, especially the merge part of the algorithm.</p>
<h3>3. Slower than insertion and bubble sort for nearly sorted input</h3>
<p>Again it is very important to know the input data. Indeed if the input is nearly sorted the insertion sort or bubble sort can be faster. Note that in the best case insertion and bubble sort complexity is O(n), while merge sort's best case is O(n*log(n)).</p>
<p>As a conclusion I can say that merge sort is practically one of the best sorting algorithms because it's easy to implement and fast, so it must be considered by every developer!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
<li><a href="/2010/07/02/friday-algorithms-javascript-merge-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Merge Sort">Friday Algorithms: JavaScript Merge 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/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/03/05/computer-algorithms-merge-sort/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Shell Sort</title>
		<link>/2012/02/27/computer-algorithms-shell-sort/</link>
		<comments>/2012/02/27/computer-algorithms-shell-sort/#comments</comments>
		<pubDate>Mon, 27 Feb 2012 20:44:54 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Adaptive sort]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[Comb sort]]></category>
		<category><![CDATA[Combinatorics]]></category>
		<category><![CDATA[Donald Shell]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[Knuth]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[Order theory]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pratt]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Shell sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>

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

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

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

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

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

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

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

		<guid isPermaLink="false">/?p=1780</guid>
		<description><![CDATA[Bubble Sort This is one of the most slowest algorithms for sorting, but it&#8217;s extremely well known because of its easy to implement nature. However as I wrote past Fridays there are lots of sorting algorithms which are really fast, like the quicksort or mergesort. In the case of bubble sort the nature of the &#8230; <a href="/2010/07/09/friday-algorithms-javascript-bubble-sort/" class="more-link">Continue reading <span class="screen-reader-text">Friday Algorithms: JavaScript Bubble Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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="/2010/06/18/friday-algorithms-iterative-quicksort/" rel="bookmark" title="Friday Algorithms: Iterative Quicksort">Friday Algorithms: Iterative Quicksort </a></li>
<li><a href="/2010/07/02/friday-algorithms-javascript-merge-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Merge Sort">Friday Algorithms: JavaScript Merge 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>Bubble Sort</h2>
<p><a href="/wp-content/uploads/2010/07/unsorted.jpg"><img class="alignleft size-full wp-image-1788" title="unsorted" src="/wp-content/uploads/2010/07/unsorted.jpg" alt="Unsorted Array" width="250" height="333" srcset="/wp-content/uploads/2010/07/unsorted.jpg 250w, /wp-content/uploads/2010/07/unsorted-225x300.jpg 225w" sizes="(max-width: 250px) 100vw, 250px" /></a></p>
<p>This is one of the most slowest algorithms for sorting, but it&#8217;s extremely well known because of its easy to implement nature. However as I wrote past Fridays there are lots of sorting algorithms which are really fast, like the <a title="Iterative Quicksort" href="/2010/06/18/friday-algorithms-iterative-quicksort/" target="_blank">quicksort</a> or <a title="Merge Sort" href="/2010/07/02/friday-algorithms-javascript-merge-sort/" target="_blank">mergesort</a>. In the case of bubble sort the nature of the algorithm is described in its name. The smaller element goes to the top (beginning) of the array as a bubble goes to the top of the water.</p>
<p>There is a cool animation showing how bubble sort works in compare to the quick sort and you can practically see how slow is bubble sort because of all the comparing.</p>
<p><a href="http://www.youtube.com/watch?v=vxENKlcs2Tw">QuickSort vs. BubbleSort</a></p>
<h2>Pseudo Code</h2>
<p>Actually what I&#8217;d like to show you is how you can move from pseudo code to code in practice. Here&#8217;s the pseudo code from <a href="http://en.wikipedia.org/wiki/Bubble_sort" title="BubbleSort Wikipedia" target="_blank">Wikipedia</a>.</p>
<pre lang="javascript">
procedure bubbleSort( A : list of sortable items ) defined as:
  do
    swapped := false
    for each i in 0 to length(A) - 2 inclusive do:
      if A[i] > A[i+1] then
        swap( A[i], A[i+1] )
        swapped := true
      end if
    end for
  while swapped
end procedure
</pre>
<h2>JavaScript Source</h2>
<pre lang="javascript">
var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];

function bubbleSort(a)
{
    var swapped;
    do {
        swapped = false;
        for (var i=0; i < a.length-1; i++) {
            if (a[i] > a[i+1]) {
                var temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
}

bubbleSort(a);
console.log(a);
</pre>
<p>As a result you&#8217;ve a sorted array!</p>
<p><a href="/wp-content/uploads/2010/07/sorted.jpg"><img class="aligncenter size-full wp-image-1790" title="sorted" src="/wp-content/uploads/2010/07/sorted.jpg" alt="Sorted Array" width="430" height="353" srcset="/wp-content/uploads/2010/07/sorted.jpg 430w, /wp-content/uploads/2010/07/sorted-300x246.jpg 300w" sizes="(max-width: 430px) 100vw, 430px" /></a></p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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="/2010/06/18/friday-algorithms-iterative-quicksort/" rel="bookmark" title="Friday Algorithms: Iterative Quicksort">Friday Algorithms: Iterative Quicksort </a></li>
<li><a href="/2010/07/02/friday-algorithms-javascript-merge-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Merge Sort">Friday Algorithms: JavaScript Merge 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>/2010/07/09/friday-algorithms-javascript-bubble-sort/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
