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