<?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>Best worst and average case &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/best-worst-and-average-case/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: Order Statistics</title>
		<link>/2012/05/28/computer-algorithms-order-statistics-the-algorithm/</link>
		<comments>/2012/05/28/computer-algorithms-order-statistics-the-algorithm/#respond</comments>
		<pubDate>Mon, 28 May 2012 19:37:00 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Best worst and average case]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Selection algorithm]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[then search]]></category>

		<guid isPermaLink="false">/?p=3149</guid>
		<description><![CDATA[Introduction We know that finding the minimum in a list of integers is a fairly simple task, but what about finding the i-th smallest element? Then the task isn’t that trivial and we have to think for a different approach. First of all there are some very basic and intuitive approaches. Since finding the minimum &#8230; <a href="/2012/05/28/computer-algorithms-order-statistics-the-algorithm/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Order Statistics</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
<li><a href="/2012/03/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
<li><a href="/2010/06/11/friday-algorithms-quicksort-difference-between-php-and-javascript/" rel="bookmark" title="Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript">Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript </a></li>
<li><a href="/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>We know that <a href="/2012/05/21/computer-algorithms-minimum-and-maximum/" title="Computer Algorithms: Minimum and Maximum">finding the minimum in a list of integers</a> is a fairly simple task, but what about finding the i-th smallest element? Then the task isn’t that trivial and we have to think for a different approach. </p>
<p>First of all there are some very basic and intuitive approaches. Since finding the minimum is so easy, can we just find the minimum, than exclude it from the list and then search the minimum again until we find the i-th smallest element.</p>
<p><figure id="attachment_3164" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/1.-Finding-the-Minimums.png"><img src="/wp-content/uploads/2012/05/1.-Finding-the-Minimums.png" alt="Finding the Minimums" title="Finding the Minimums" width="621" height="302" class="size-full wp-image-3164" srcset="/wp-content/uploads/2012/05/1.-Finding-the-Minimums.png 621w, /wp-content/uploads/2012/05/1.-Finding-the-Minimums-300x145.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text"> </figcaption></figure><span id="more-3149"></span></p>
<p>That is a pure brute-force-like algorithm and it is extremely slow. In this case if we’re looking for the 99-th smallest element into an array of 100 items it will be quite inefficient. In other words this isn’t the best approach.</p>
<p>Another fairly intuitive approach is to sort the list in first place and then search the i-th element. </p>
<figure id="attachment_3163" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/2.-Sort-and-Seach.png"><img src="/wp-content/uploads/2012/05/2.-Sort-and-Seach.png" alt="Sort and Seach" title="Sort and Seach" width="621" height="299" class="size-full wp-image-3163" srcset="/wp-content/uploads/2012/05/2.-Sort-and-Seach.png 621w, /wp-content/uploads/2012/05/2.-Sort-and-Seach-300x144.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">First we can sort the list and then search for the i-th element!</figcaption></figure>
<p>This is better than the our first attempt because we&#8217;ll need the time to sort the array and then search (in linear time) the i-th element.</p>
<p>In this case we need to find out which of the sorting algorithms we will use. Will it be <a href="/2012/03/05/computer-algorithms-merge-sort/" title="Computer Algorithms: Merge Sort">merge sort</a> (with constant O(n.lg(n)) complexity) or <a href="/2012/03/13/computer-algorithms-quicksort/" title="Computer Algorithms: Quicksort">quicksort</a> (with O(n<sup>2</sup>) in the worst case, but O(n.lg(n)) average complexity) or <a href="/2012/02/20/computer-algorithms-bubble-sort/" title="Computer Algorithms: Bubble Sort">bubble sort</a> (O(n^n) in the best-case scenario) it’s a developer choice.</p>
<p>However there is one very clever and yet more efficient approach, based on some observations.</p>
<h2>Overview</h2>
<p>If we’re looking for the i-th element and we decided that the list must be sorted first, we don’t need to fully sort it in order to find the desired element. </p>
<p>In case the list is sorted it’s easy to find which is the i-th element. However if the i-th element is in its place, the only thing we need to know is that the items on the left side of the i-th element are smaller and the items on the right side are greater. We don’t need the left and the right side ordered.</p>
<figure id="attachment_3162" style="width: 619px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/3.-Dont-need-ordered-sub-lists.png"><img src="/wp-content/uploads/2012/05/3.-Dont-need-ordered-sub-lists.png" alt="Don&#039;t need ordered sub-lists" title="Don&#039;t need ordered sub-lists" width="619" height="279" class="size-full wp-image-3162" srcset="/wp-content/uploads/2012/05/3.-Dont-need-ordered-sub-lists.png 619w, /wp-content/uploads/2012/05/3.-Dont-need-ordered-sub-lists-300x135.png 300w" sizes="(max-width: 619px) 100vw, 619px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>In the other hand this approach looks very much like quicksort. There during the sorting process we put the items smaller than the “pivot” on its left and the items greater than the pivot on its right. After that partitioning we executed quicksort on the left and on the right sub-lists.</p>
<p>Here the approach is similar with very small changes. First we choose a pivot. Then we make two partitions of the list &#8211; one left sub-list with all the elements with smaller values than the pivot and one right sub-list with all the elements with a greater value than the pivot. </p>
<figure id="attachment_3161" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/4.-Choose-a-pivot-and-partition.png"><img src="/wp-content/uploads/2012/05/4.-Choose-a-pivot-and-partition.png" alt="Choose a pivot and partition" title="Choose a pivot and partition" width="618" height="229" class="size-full wp-image-3161" srcset="/wp-content/uploads/2012/05/4.-Choose-a-pivot-and-partition.png 618w, /wp-content/uploads/2012/05/4.-Choose-a-pivot-and-partition-300x111.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">Just like quicksort we chose a pivot and then we partition the list into two sub-lists!</figcaption></figure>
<p>Now we check the length of the left sub-list. If it is greater than i we continue recursively with the left sub-list and again we’re searching for the i-th element.</p>
<p>In case the length of the left sub-list is smaller than i, we continue with the right sub-list. However this time we don’t search for the i-th element, but for the i &#8211; length(LEFT). </p>
<h2>Implementation</h2>
<p>The following implementation is in <a href="/category/php/" title="PHP on stoimen.com">PHP</a>. It’s important to note that at each step we need two non-empty sub-list. That is why we take the pivot (by extracting the last item of the list) and then making two sub-lists. In case one of the sub-lists is empty we append the pivot in it. Thus we’re always partitioning the list into two non-empty sub-lists. </p>
<pre lang="PHP">
$list = array(3,4,5,7,8,2,5,6,9,0,1);

function partition($list, $pivot)
{
	$left = $right = array();
	
	$len = count($list);
	for ($i = 0; $i < $len; $i++) {
		if ($list[$i] <= $pivot) {
			$left[] = $list[$i];
		} else {
			$right[] = $list[$i];
		}
	}

	if (count($left) == 0) {
		$left[] = $pivot;
	} else {
		$right[] = $pivot;
	} 
	
	return array($left, $right);
}

function order_statistic($list, $i)
{
	if (count($list) == 1) {
		return $list[0];
	}
	
	// ceate a non empty partitions
	// extract the pivot from the list and
	// in case one of the sub-lists is empty
	// add the pivot there!
	$pivot = array_pop($list);
	list($left, $right) = partition($list, $pivot);
	
	if (count($left) >= $i) {
		return order_statistic($left, $i);
	} else {
		return order_statistic($right, $i - count($left));
	}
}

// 4
echo order_statistic($list, 5);
</pre>
<h2>Application</h2>
<p>Finding the minimum and maximum is easy, however sometimes we don&#8217;t search for them, but for the second, third or i-th smallest element. Then our task becomes a bit more difficult. This algorithm can be useful in many practical cases and shows us how different kind of algorithms may be related &#8211; exactly as this algorithm is related to quicksort in its principles.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
<li><a href="/2012/03/05/computer-algorithms-merge-sort/" rel="bookmark" title="Computer Algorithms: Merge Sort">Computer Algorithms: Merge Sort </a></li>
<li><a href="/2010/06/11/friday-algorithms-quicksort-difference-between-php-and-javascript/" rel="bookmark" title="Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript">Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript </a></li>
<li><a href="/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/05/28/computer-algorithms-order-statistics-the-algorithm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Radix Sort</title>
		<link>/2012/03/19/computer-algorithms-radix-sort/</link>
		<comments>/2012/03/19/computer-algorithms-radix-sort/#comments</comments>
		<pubDate>Mon, 19 Mar 2012 20:54:00 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Best worst and average case]]></category>
		<category><![CDATA[Bubble sort]]></category>
		<category><![CDATA[Bucket sort]]></category>
		<category><![CDATA[faster algorithm]]></category>
		<category><![CDATA[faster linear complexity algorithms]]></category>
		<category><![CDATA[Heapsort]]></category>
		<category><![CDATA[input algorithms]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[Introduction Algorithms]]></category>
		<category><![CDATA[linear complexity algorithms]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[purpose sorting algorithms]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Radix sort]]></category>
		<category><![CDATA[Shell sort]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>

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

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

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

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

radix_sort(&$list);

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

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

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

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

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

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

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

	return $result;  
}  

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