<?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>Heapsort &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/heapsort/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: Heap and Heapsort</title>
		<link>/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/</link>
		<comments>/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/#comments</comments>
		<pubDate>Tue, 07 Aug 2012 12:33:15 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Binary heap]]></category>
		<category><![CDATA[Binary tree]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Discrete mathematics]]></category>
		<category><![CDATA[Heap]]></category>
		<category><![CDATA[Heapsort]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[next]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Priority queue]]></category>
		<category><![CDATA[purpose algorithm]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[sorting algorithm]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Tree]]></category>

		<guid isPermaLink="false">/?p=3278</guid>
		<description><![CDATA[Introduction Heapsort is one of the general sorting algorithms that performs in O(n.log(n)) in the worst-case, just like merge sort and quicksort, but sorts in place &#8211; as quicksort. Although quicksort’s worst-case sorting time is O(n2) it’s often considered that it beats other sorting algorithms in practice. Thus in practice quicksort is “faster” than heapsort. &#8230; <a href="/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Heap and Heapsort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" rel="bookmark" title="Computer Algorithms: Balancing a Binary Search Tree">Computer Algorithms: Balancing a Binary Search Tree </a></li>
<li><a href="/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/" rel="bookmark" title="Computer Algorithms: Finding the Lowest Common Ancestor">Computer Algorithms: Finding the Lowest Common Ancestor </a></li>
<li><a href="/2012/06/22/computer-algorithms-binary-search-tree-data-structure/" rel="bookmark" title="Computer Algorithms: Binary Search Tree">Computer Algorithms: Binary Search Tree </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>Heapsort is one of the general sorting algorithms that performs in O(n.log(n)) in the worst-case, just like <a href="/2012/03/05/computer-algorithms-merge-sort/" title="Merge sort explained">merge sort</a> and <a href="/2012/03/13/computer-algorithms-quicksort/" title="Quicksort explained">quicksort</a>, but sorts in place &#8211; as quicksort. Although quicksort’s worst-case sorting time is O(n<sup>2</sup>) it’s often considered that it beats other sorting algorithms in practice. Thus in practice quicksort is “faster” than heapsort. In the same time developers tend to consider heapsort as more difficult to implement than other n.log(n) sorting algorithms.</p>
<p>In the other hand heapsort uses a special data structure, called heap, in order to sort items in place and this data structure is quite useful in some specific cases. Thus to understand heapsort we first need to understand what is a heap.</p>
<p>So first let&#8217;s take a look at what is a heap.</p>
<h2>Overview</h2>
<p>A heap is a complete binary tree, where all the parents are greater than their children (max heap). If all the children are greater than their parents it is considered to call the heap a min-heap. But first what is a complete binary tree? Well, this is a binary tree, where all the levels are full, except the last one, where all the items are placed on the left (just like on the image below).</p>
<p><figure id="attachment_3295" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/1.-Complete-Binary-Tree.png"><img src="/wp-content/uploads/2012/08/1.-Complete-Binary-Tree.png" alt="Complete Binary Tree" title="Complete Binary Tree" width="619" height="345" class="size-full wp-image-3295" srcset="/wp-content/uploads/2012/08/1.-Complete-Binary-Tree.png 619w, /wp-content/uploads/2012/08/1.-Complete-Binary-Tree-300x167.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text">A complete binary tree is a structure where all the levels are completely full, except the last level, where all the items are placed on the left!</figcaption></figure><span id="more-3278"></span></p>
<p>Combined with the fact that each node contains a greater key than its children, a heap may look like the tree on the following diagram.</p>
<figure id="attachment_3294" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/2.-Heap.png"><img src="/wp-content/uploads/2012/08/2.-Heap.png" alt="Heap" title="Heap" width="621" height="359" class="size-full wp-image-3294" srcset="/wp-content/uploads/2012/08/2.-Heap.png 621w, /wp-content/uploads/2012/08/2.-Heap-300x173.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">In a max-heap each node contains a greater value than its children. Respectively in a min-heap each node contains a smaller value than its parent!</figcaption></figure>
<p>The thing is that if we put indices next to each node of this tree, starting from the root (index 1) and continuing from left to right on each level, we’ll get the following tree.</p>
<figure id="attachment_3293" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/3.-Heap-Indexes.png"><img src="/wp-content/uploads/2012/08/3.-Heap-Indexes.png" alt="Heap Indices" title="Heap Indices" width="618" height="360" class="size-full wp-image-3293" srcset="/wp-content/uploads/2012/08/3.-Heap-Indexes.png 618w, /wp-content/uploads/2012/08/3.-Heap-Indexes-300x174.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Putting indices right to each node reveals the secret of the heap. The i-th node has left child exactly with the index 2*i, and right child with index 2*i+1! This is a great opportunity to put this tree into an array!</figcaption></figure>
<p>Now if we take a closer look to the picture above we can see that the indices of a node and its children are closely related. Thus for a node of an index <em>i</em> we see that its left child has the index <em>2*i</em>, while its right child’s index is <em>2*i + 1</em>.</p>
<p><em>This particular order gives us the possibility to store each heap in an array.</em></p>
<figure id="attachment_3292" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/4.-Heap-as-an-Array.png"><img src="/wp-content/uploads/2012/08/4.-Heap-as-an-Array.png" alt="Heap as an Array" title="Heap as an Array" width="620" height="399" class="size-full wp-image-3292" srcset="/wp-content/uploads/2012/08/4.-Heap-as-an-Array.png 620w, /wp-content/uploads/2012/08/4.-Heap-as-an-Array-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The heap tree can be easily represented as an array!</figcaption></figure>
<p>Since in a heap its greater element is in the root of the tree (for max-heap, respectively in a min-heap its smallest element is the root) we need to answer two questions. </p>
<ol>
<li>How to build a heap out of an ordinary array?</li>
<li>After extracting the root, which is the greatest (smallest) item, how can we rebuild the heap in order to keep it a heap again?</li>
</ol>
<p>First let’s try to answer the first question. How to build a heap? Well, let’s forget about the array for a while and let’s take a look on a ordinary binary tree with only three nodes.</p>
<figure id="attachment_3291" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/5.-Heapify.png"><img src="/wp-content/uploads/2012/08/5.-Heapify.png" alt="Heapify" title="Heapify" width="620" height="317" class="size-full wp-image-3291" srcset="/wp-content/uploads/2012/08/5.-Heapify.png 620w, /wp-content/uploads/2012/08/5.-Heapify-300x153.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Fixing a node and its children in order to form a valid Heap is often called heapify!</figcaption></figure>
<p>We see that the three green nodes destroy the structure of our heap, because the root (1) is smaller than its children (4) and (5). Thus we need to fix this problem and what we’re going to do is to swap the root with its biggest child. </p>
<figure id="attachment_3290" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/6.-Heapify-Part-1.png"><img src="/wp-content/uploads/2012/08/6.-Heapify-Part-1.png" alt="Heapify Part 2" title="Heapify Part 2" width="620" height="399" class="size-full wp-image-3290" srcset="/wp-content/uploads/2012/08/6.-Heapify-Part-1.png 620w, /wp-content/uploads/2012/08/6.-Heapify-Part-1-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We first need to know which is the greatest out of the three items, than in case it is not the root, swap its value with the root!</figcaption></figure>
<p>As you can see on the picture above the <em>i</em>-th item is first compared to its left child. The greater of these two items is compared to the right child. Note that we don’t swap them &#8211; we just compare them to get which one is greater. Once we find the greatest of these three values we swap them with the root in case it&#8217;s not the root value.</p>
<p>Although now these three elements form a heap, by swapping the root with one of its children may destroy the heap constructed out of this child. That is why we continue the same procedure with it.</p>
<p>This actually gives us the procedure to heapify the three nodes constructed out of the <em>i</em>-th item and its children. However to build a heap from an arbitrary array we should perform this operation starting from floor(len[A] / 2) down to the first item in the array.</p>
<figure id="attachment_3289" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/7.-Random-Array-to-Heap.png"><img src="/wp-content/uploads/2012/08/7.-Random-Array-to-Heap.png" alt="Random Array to Heap" title="Random Array to Heap" width="620" height="399" class="size-full wp-image-3289" srcset="/wp-content/uploads/2012/08/7.-Random-Array-to-Heap.png 620w, /wp-content/uploads/2012/08/7.-Random-Array-to-Heap-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Building a random array into a heap isn&#8217;t that difficult since we know that half of the complete tree items lay in it&#8217;s lowest level! Thus we start from floor(len[A] / 2)!</figcaption></figure>
<p>Why? Well, a complete binary tree with a full last level contains n/2 + 1 nodes in it. They don’t have children, thus we don’t need to check them &#8211; they are &#8220;sorted&#8221;. Indeed if we start from an item on the right of floor(len[A] / 2) there won’t be items with indices <em>2*i</em> and <em>2*i + 1</em>.</p>
<h2>Code</h2>
<p>So far we know how to build the heap. Next thing is to swap the first and the last element of the array and rebuild the heap. Here’s the PHP code of how to do this.</p>
<pre lang="PHP">
$a = array(1, 6, 3, 8, 2, 5, 4);

function heapify(&$a, &$i, &$heap_size)
{
    $l = $i*2 + 1;
    $r = $i*2 + 2;
    
    if ($l < $heap_size &#038;&#038; $a[$i] < $a[$l]) {
        $largest = $l;
    } else {
        $largest = $i;
    }
    
    if ($r < $heap_size &#038;&#038; $a[$largest] < $a[$r]) {
        $largest = $r;
    }
    
    if ($largest != $i) {
        $t = $a[$i];
        $a[$i] = $a[$largest];
        $a[$largest] = $t;
        
        heapify($a, $largest, $heap_size);
    }
}

function build_heap(&#038;$a, &#038;$heap_size)
{
    $len = floor($heap_size / 2);
    for ($i = $len; $i > -1; $i--) {
        heapify($a, $i, $heap_size);
    }
}

function heapsort(&$a)
{
    $heap_size = count($a);
    build_heap($a, $heap_size);
    
    while ($heap_size--) {
        $t = $a[$heap_size];
        $a[$heap_size] = $a[0];
        $a[0] = $t;
        build_heap($a, $heap_size);
    }
}

// 1 2 3 4 5 6 8
heapsort($a);
</pre>
<h2>Complexity</h2>
<p>OK, the last question is &#8211; how do we know that this algorithm sorts in place in n.log(n) time? Let’s explore the algorithm one more time. The heapify worst-case is when we start from the root down to the lowest level of the tree. In these terms if the tree height is <strong>h</strong>, the time is O(h), but because the tree is balanced (complete) the time in terms of n is O(log(n)). </p>
<p>In the other hand to build a heap we walk from floor(len[A] / 2) to 0, which makes it run in O(n.log(n)). However there is only one case when the heapify may run in log(n), and that is when it starts from the root, so it’s not absolutely true that building the heap runs in n.log(n).</p>
<p>Indeed heapify depend on the level it has been started. It doesn’t run for the last ceil(n/2) items and it runs in O(1) for another 2<sup>h-1</sup>. Thus in practice we can build a heap in O(n). </p>
<p>Once we have the heap built, the only thing to do is to extract its first element and rebuild &#8211; heapify from the first item. This makes the sorting algorithm run in O(n.log(n)) &#8211; just like quicksort and mergesort.</p>
<h2>Application</h2>
<p>As I said in the beginning of this post quicksort is often the fastest general purpose algorithm in practice. This makes both merge sort and heapsort not so popular. However heapsort introduces an interesting data structure which can help us in many other cases. </p>
<p>It’s initially used to implement priority queues. What is great about a heap is that after we build it, which we know how to do in linear time, we can extract the greatest value &#8211; thus taking the highest priority task. Then with rebuilding the heap we can extract the next priority and so on, without fully sorting the array. </p>
<p>This makes the heapsort the only sorting algorithm that can sort the first <strong>k</strong> items out of a set of <strong>n</strong> items without sorting the whole set.</p>
<p>Indeed let’s say we have a set of positive integers and we’d like to get the biggest sum out of three items. Obviously we can sort the array and take the greatest three numbers, but this will cost us n.log(n) time, while using heapsort we can do it much faster! And all this without extra space &#8211; in place!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" rel="bookmark" title="Computer Algorithms: Balancing a Binary Search Tree">Computer Algorithms: Balancing a Binary Search Tree </a></li>
<li><a href="/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/" rel="bookmark" title="Computer Algorithms: Finding the Lowest Common Ancestor">Computer Algorithms: Finding the Lowest Common Ancestor </a></li>
<li><a href="/2012/06/22/computer-algorithms-binary-search-tree-data-structure/" rel="bookmark" title="Computer Algorithms: Binary Search Tree">Computer Algorithms: Binary Search Tree </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/08/07/computer-algorithms-heap-and-heapsort-data-structure/feed/</wfw:commentRss>
		<slash:comments>7</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: 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>
	</channel>
</rss>
