<?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>faster algorithm &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/faster-algorithm/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: Adding Large Integers</title>
		<link>/2013/01/07/computer-algorithms-adding-large-integers/</link>
		<comments>/2013/01/07/computer-algorithms-adding-large-integers/#comments</comments>
		<pubDate>Mon, 07 Jan 2013 15:16:47 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Abstract algebra]]></category>
		<category><![CDATA[Addition]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Arbitrary-precision arithmetic]]></category>
		<category><![CDATA[Binary numeral system]]></category>
		<category><![CDATA[Computer arithmetic]]></category>
		<category><![CDATA[Elementary arithmetic]]></category>
		<category><![CDATA[Elementary number theory]]></category>
		<category><![CDATA[faster algorithm]]></category>
		<category><![CDATA[Integer]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Number]]></category>
		<category><![CDATA[Radix sort]]></category>

		<guid isPermaLink="false">/?p=3525</guid>
		<description><![CDATA[Introduction We know how to add two integers using a perfectly simple and useful algorithm learned from school or even earlier. This is perhaps one of the very first techniques we learn in mathematics. However we need to answer few questions. First of all do computers use the same technique, since they use binary representation &#8230; <a href="/2013/01/07/computer-algorithms-adding-large-integers/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Adding Large Integers</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="/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/05/15/computer-algorithms-karatsuba-fast-multiplication/" rel="bookmark" title="Computer Algorithms: Karatsuba Fast Multiplication">Computer Algorithms: Karatsuba Fast Multiplication </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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We know how to add two integers using a perfectly simple and useful algorithm learned from school or even earlier. This is perhaps one of the very first techniques we learn in mathematics. However we need to answer few questions. First of all do computers use the same technique, since they use binary representation of numbers? Is there a faster algorithm used by computers? What about boundaries and large integers?</p>
<h2>Overview</h2>
<p>Let’s start by explaining how we humans add two numbers. An important fact is that by adding two single-digit numbers we get at most two digit number. This can be proven by simply realizing that 9+9 = 18. This fact lays down in the way we add integers. Here’s how.</p>
<p><img src="https://docs.google.com/drawings/pub?id=11pxzTffU-mVas5OYWiFg2sdSUAXa-QvBD1pSewNao3A&amp;w=620&amp;h=399"></p>
<p>We just line-up the integers on their right-most digit and we start adding them in a column. In case we got a sum greater than 9 (let’s say 14) we keep only the right-most digit (the 4) and the 1 is added to the next sum.</p>
<p>Thus we get to the simple fact that by adding two n-digit integers we can have either an n-digit integer or a n+1 digit integer. As an example we see that by adding 53 + 35 (two 2-digit integers) we get 88, which is again 2-digit integer, but 53 + 54 result in 107, which is 3 digit integer. </p>
<p>That fact is practically true, as I mentioned above, for each pair of n-digit integers.</p>
<h3>What about binary numbers?</h3>
<p>In fact binaries can be added by using the exact same algorithm. At the example below we add two integers represented as binary numbers.</p>
<p><img src="https://docs.google.com/drawings/pub?id=1E376ILBpXg5fUU8JbxiKwIcSa8DxSDtaIjqVsCJCjWk&amp;w=620&amp;h=399"></p>
<p>As a matter of fact this algorithm is absolutely wonderful, because it works not only on decimals and binaries but in any base B.</p>
<p>Of course computers tend to perform better when adding integers that “fit” the machine word. However as we can see later this isn’t always the case and sometimes we need to add larger numbers that exceed the type boundaries.</p>
<h3>What about big integers?</h3>
<p>Since we know how to add “small” integers, it couldn’t be so hard to apply the same algorithm on big integers. The only problem is that the addition will be slower and sometimes (done by humans) can be error prone. </p>
<p>So practically the algorithm is the same, but we can’t just put a 1 billion integer into a standard computer type INT, right? That means that the tricky part here is the way we represent integers in our application. A common solution is to store the “big” integer into an array, thus each digit will be a separate array item. Then the operation of addition will be simple enough to be applied.</p>
<h2>Complexity</h2>
<p>When we talk about an algorithm that is so well known by every human being (or almost every) a common question is “is there anything faster” or “do computers use a different algorithm”. The answer may be surprising to someone, but unfortunately that is the fastest (optimal) algorithm for number addition. </p>
<p>Practically there’s nothing to optimize here. We just read the two n-digit numbers (O(n)), we apply “simple” addition to each digit and we carry over the 1 from the sums greater than 9 to the next &#8220;simple&#8221; addition. We don’t have loops or any complex operation in order to search for an optimization niche.</p>
<h2>Application</h2>
<p>It’s strange how often this algorithm is asked on coding interviews. Perhaps the catch is whether the interviewed person will start to look for a faster approach?! Thus is cool to know that this algorithm is optimal.</p>
<p>Sometimes we may ask ourselves why we humans use decimals. It’s considered because we have 10 fingers on our hands and this is perhaps true.</p>
<p>An interesting fact though, is that the Mayas (who barely predicted the end of the world a couple of weeks ago) used a system of a base 20. That is logical, since we have not 10, but total of 20 fingers considering our legs.</p>
<p>Finally, this algorithm may seem to easy to be explained but it lays down in more complex algorithms.</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="/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/05/15/computer-algorithms-karatsuba-fast-multiplication/" rel="bookmark" title="Computer Algorithms: Karatsuba Fast Multiplication">Computer Algorithms: Karatsuba Fast Multiplication </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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2013/01/07/computer-algorithms-adding-large-integers/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Shortest Path in a Directed Acyclic Graph</title>
		<link>/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/</link>
		<comments>/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/#comments</comments>
		<pubDate>Sun, 28 Oct 2012 19:24:22 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Bellman–Ford algorithm]]></category>
		<category><![CDATA[Dijkstra's algorithm]]></category>
		<category><![CDATA[Directed acyclic graph]]></category>
		<category><![CDATA[Distance]]></category>
		<category><![CDATA[faster algorithm]]></category>
		<category><![CDATA[Ford Motor Company]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[Longest path problem]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Network theory]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Routing algorithms]]></category>
		<category><![CDATA[Shortest path problem]]></category>
		<category><![CDATA[Theoretical computer science]]></category>
		<category><![CDATA[Topological sorting]]></category>

		<guid isPermaLink="false">/?p=3419</guid>
		<description><![CDATA[Introduction We saw how to find the shortest path in a graph with positive edges using the Dijkstra’s algorithm. We also know how to find the shortest paths from a given source node to all other nodes even when there are negative edges using the Bellman-Ford algorithm. Now we’ll see that there’s a faster algorithm &#8230; <a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Shortest Path in a Directed Acyclic Graph</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/12/03/computer-algorithms-longest-increasing-subsequence/" rel="bookmark" title="Computer Algorithms: Longest Increasing Subsequence">Computer Algorithms: Longest Increasing Subsequence </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We saw how to find the shortest path in a graph with positive edges using the <a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Dijkstra’s algorithm</a>. We also know how to find the shortest paths from a given source node to all other nodes even when there are negative edges using <a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">the Bellman-Ford algorithm</a>. Now we’ll see that there’s a faster algorithm running in linear time that can find the shortest paths from a given source node to all other reachable vertices in a directed acyclic graph, also known as a DAG.</p>
<p>Because the DAG is acyclic we don’t have to worry about negative cycles. As we already know it’s pointless to speak about shortest path in the presence of negative cycles because we can “loop” over these cycles and practically our path will become shorter and shorter.</p>
<figure id="attachment_3431" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/1.-Negative-Cycles.png"><img src="/wp-content/uploads/2012/10/1.-Negative-Cycles.png" alt="Negative Cycles" title="Negative Cycles" width="620" height="399" class="size-full wp-image-3431" srcset="/wp-content/uploads/2012/10/1.-Negative-Cycles.png 620w, /wp-content/uploads/2012/10/1.-Negative-Cycles-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">The presence of a negative cycles make our atempt to find the shortest path pointless!</figcaption></figure>
<p>Thus we have two problems to overcome with Dijkstra and the Bellman-Ford algorithms. First of all we needed only positive weights and on the second place we didn’t want cycles. Well, we can handle both cases in this algorithm.<span id="more-3419"></span></p>
<h2>Overview</h2>
<p>The first thing we know about DAGs is that they can easily be topologically sorted. <a href="/2012/10/01/computer-algorithms-topological-sort-of-a-graph/" title="Computer Algorithms: Topological Sort of a Graph">Topological sort</a> can be used in many practical cases, but perhaps the mostly used one is when trying to schedule dependent tasks.</p>
<figure id="attachment_3429" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/2.-Topological-Sort.png"><img src="/wp-content/uploads/2012/10/2.-Topological-Sort.png" alt="Topological Sort" title="Topological Sort" width="620" height="399" class="size-full wp-image-3429" srcset="/wp-content/uploads/2012/10/2.-Topological-Sort.png 620w, /wp-content/uploads/2012/10/2.-Topological-Sort-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Topological sort is often used to &#8220;sort&#8221; dependent tasks!</figcaption></figure>
<p>After a topological sort we end with a list of vertices of the DAG and we’re sure that if there’s an edge (u, v), u will precede v in the topologically sorted list.</p>
<figure id="attachment_3430" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/10/3.-Topological-Sort-part-2.png"><img src="/wp-content/uploads/2012/10/3.-Topological-Sort-part-2.png" alt="Topological Sort (part 2)" title="Topological Sort (part 2)" width="620" height="399" class="size-full wp-image-3430" srcset="/wp-content/uploads/2012/10/3.-Topological-Sort-part-2.png 620w, /wp-content/uploads/2012/10/3.-Topological-Sort-part-2-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">If there&#8217;s an edge (u,v) then u must precede v. This results in the more general case from the image. There&#8217;s no edge between B and D, but B precedes D!</figcaption></figure>
<p>This information is precious and the only thing we need to do is to pass through this sorted list and to calculate distances for a shortest paths just like the algorithm of Dijkstra.</p>
<p>OK, so let’s summarize this algorithm:<br />
&#8211;	First we must topologically sort the DAG;<br />
&#8211;	As a second step we set the distance to the source to 0 and infinity to all other vertices;<br />
&#8211;	Then for each vertex from the list we pass through all its neighbors and we check for shortest path;</p>
<p>It’s pretty much like the Dijkstra’s algorithm with the main difference that we used a priority queue then, while this time we use the list from the topological sort.</p>
<h2>Code</h2>
<p>This time the code is actually a pseudocode. Altough all the examples so far was in PHP, perhaps pseudocode is easier to understand and doesn&#8217;t bind you in a specific language implementation. Also if you don&#8217;t feel comforatable with the given programming language it can be more difficult for you to understand the code than by reading pseudocode.</p>
<pre lang="PHP line="1">
1. Topologically sort G into L;
2. Set the distance to the source to 0;
3. Set the distances to all other vertices to infinity;
4. For each vertex u in L
5.    - Walk through all neighbors v of u;
6.    - If dist(v) > dist(u) + w(u, v) 
7.       - Set dist(v) <- dist(u) + w(u, v);
</pre>
<h2>Application</h2>
<p>It’s clear why and where we must use this algorithm. The only problem is that we must be sure that the graph doesn’t have cycles. However if we’re aware of how the graph is created we may have some additional information if there are cycles or not – then this linear time algorithm can be very applicable. </p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/10/22/computer-algorithms-bellman-ford-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Bellman-Ford Shortest Path in a Graph">Computer Algorithms: Bellman-Ford Shortest Path in a Graph </a></li>
<li><a href="/2012/10/08/computer-algorithms-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Graph">Computer Algorithms: Shortest Path in a Graph </a></li>
<li><a href="/2012/10/15/computer-algorithms-dijkstra-shortest-path-in-a-graph/" rel="bookmark" title="Computer Algorithms: Dijkstra Shortest Path in a Graph">Computer Algorithms: Dijkstra Shortest Path in a Graph </a></li>
<li><a href="/2012/12/03/computer-algorithms-longest-increasing-subsequence/" rel="bookmark" title="Computer Algorithms: Longest Increasing Subsequence">Computer Algorithms: Longest Increasing Subsequence </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/feed/</wfw:commentRss>
		<slash:comments>1</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: Linear Search in Sorted Lists</title>
		<link>/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/</link>
		<comments>/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/#comments</comments>
		<pubDate>Fri, 02 Dec 2011 14:20:07 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search algorithm]]></category>
		<category><![CDATA[cellular telephone]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[faster algorithm]]></category>
		<category><![CDATA[Index]]></category>
		<category><![CDATA[Linear search]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[sequential search using sentinel]]></category>
		<category><![CDATA[sorting algorithm]]></category>

		<guid isPermaLink="false">/?p=2492</guid>
		<description><![CDATA[Overview The expression &#8220;linear search in sorted lists&#8221; itself sounds strange. Why should we use this algorithm for sorted lists when there are lots of other algorithms that are far more effective? As I mentioned in my previous post the sequential search is very ineffective in most of the cases and it is primary used &#8230; <a href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Linear Search in Sorted Lists</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>The expression &#8220;linear search in sorted lists&#8221; itself sounds strange. Why should we use this algorithm for sorted lists when there are lots of other algorithms that are far more effective? As I mentioned in</p>
<p><a href="/2011/11/24/computer-algorithms-sequential-search/" title="Computer Algorithms: Sequential Search">my previous post</a> the sequential search is very ineffective in most of the cases and it is primary used for unordered lists. Indeed sometimes it is more useful first to sort the data and then use a faster algorithm like the binary search. On the other hand the analysis shows that for lists with less than ten items the linear search is much faster than the binary search. Although, for instance, binary search is more effective on sorted lists, sequential search can be a better solution in some specific cases with minor changes. The problem is that when developers hear the expression &#8220;sorted list&#8221; they directly choose an algorithm different from the linear search. Perhaps the problem lays in the way we understand what an ordered list is?</p>
<h3>What is a sorted list?</h3>
<p>We used to think that this list <strong>(1, 1, 2, 3, 5, 8, 13)</strong> is sorted. Actually we think so because it is &#8230; sorted, but the list <strong>(3, 13, 1, 3, 3.14, 1.5, -1)</strong> is also sorted, except that we don’t know how. Thus we can think that any array is sorted, although it is not always obvious how. There are basically two cases when sequential search can be very useful. First when the list is very short or when we know in advance that there are some values that are very frequently searched.<span id="more-2492"></span> Let&#8217;s say we have a very large list, with hundreds of thousands of items, but actually most of the searches in that list always find the same ten values. This additional information tells us that using a binary search will be quite ineffective in this case. A possible approach, of course, is to place those values at the front of the list and to perform a sequential search. <figure id="attachment_2523" style="width: 620px" class="wp-caption alignnone"></p>
<p><a href="/wp-content/uploads/2011/12/search.jpg"><img src="/wp-content/uploads/2011/12/search.jpg" alt="You should choose a search algorithm by carefully examining the data you search." title="magnifying glass" width="620" height="270" class="size-full wp-image-2523" srcset="/wp-content/uploads/2011/12/search.jpg 620w, /wp-content/uploads/2011/12/search-300x130.jpg 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">You should choose a search algorithm by carefully examining the data you search.</figcaption></figure> Unfortunately the search will be slow when we search for some value missing from the front of the list, but then we can use another algorithm on sorted lists. Still there is one question that should be answered. We do know that in most of the cases we search for the same values, but we do not know exactly those values. So the question is how to put the most frequently accessed values at the front of the list, since we don&#8217;t know them. Here we need some sort of auto adjustment of the list.</p>
<h2>Self-Organization</h2>
<p>Self-organization practically means that every time we search and find the desired value, we somehow change the list so the next search will be far more effective. There are basically two approaches to do that.</p>
<ol>
<li>To move the item one position forward to the front of the list;</li>
<li>To move the item directly at the front of the list; </li>
</ol>
<p>Of course it depends on your case which approach you&#8217;ll choose, but it is assumed that the second option, the one that we choose to move the item directly at the front of the list, is better. Indeed if we choose the first option and the list is (&#8230;, 24, 31) after constantly searching for those two values the array will be changing from (&#8230;, 24, 31) to (&#8230;, 31, 24) and once again to (&#8230;, 24, 31) and so on and so on. Thus a better solution is to move the desired item directly to the front of the list. Now if we look for the value of &#8220;5&#8221; in the list</p>
<p><strong>(1, 2, 4, &#8230;, 5, &#8230;, 398)</strong> it will become <strong>(5, 1, 2, &#8230;, 398)</strong> after the value is found. By choosing this approach we can be sure that as the number of searches increases, the most frequently searched values are placed at the front of the list. Now the sequential search is quite a good solution! Here&#8217;s an example of sequential search from my previous article. The only change is that after we find the desired value we need to move it to the front of the list.</p>
<p><script src="https://gist.github.com/stoimen/cc5aa136ef8d08d7c1a9.js?file=linear_search.php"></script></p>
<h2>Application</h2>
<p>Using sequential search in sorted lists can be very useful and fast, the only thing is that we need to know in advance that there are some values that are frequently searched. A typical example of this case is the contact list on your phone. Perhaps you have lots of names in there, but most of the times you search in it is to find your best friends&#8217; and family phone numbers. That is why most of the cell phone manufacturers add to their phones the ability to predefine shortcut keys for the most frequently dialed numbers. Here&#8217;s another use case. Let&#8217;s say that we have the same scenario as in my previous</p>
<p><a href="/2011/11/24/computer-algorithms-sequential-search/" title="Computer Algorithms: Sequential Search">post</a>, where username/name pairs are stored into a CSV file. We can fetch those values in a PHP array.</p>
<p>Every time a user enters the site we search for his name by his username and a welcome message is displayed. We know that some users enter the site very frequently while others do that once per month so we cannot only perform a sequential search but also we can use self-organization for the array and change the CSV file at the end.</p>
<p><script src="https://gist.github.com/stoimen/cc5aa136ef8d08d7c1a9.js?file=linear_search_v1.php"></script><br />
The result is:</p>
<pre><code>Hello, Darth Vader 
Found after 5 iterations!
Hello, Darth Vader
Found after 1 iterations!
</code></pre>
<p>Now every time Darth Vader tries to sign in, you won&#8217;t bother him to wait a lot for sure. However I bet nobody uses CSV files to store such information, but this is only an example.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
<li><a href="/2011/12/12/computer-algorithms-jump-search/" rel="bookmark" title="Computer Algorithms: Jump Search">Computer Algorithms: Jump Search </a></li>
<li><a href="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
<li><a href="/2012/01/02/computer-algorithms-interpolation-search/" rel="bookmark" title="Computer Algorithms: Interpolation Search">Computer Algorithms: Interpolation Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
