<?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>ineffective algorithm &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/ineffective-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: Topological Sort Revisited</title>
		<link>/2012/12/10/computer-algorithms-topological-sort-revisited/</link>
		<comments>/2012/12/10/computer-algorithms-topological-sort-revisited/#comments</comments>
		<pubDate>Mon, 10 Dec 2012 15:45:16 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Graphs]]></category>
		<category><![CDATA[Adjacency list]]></category>
		<category><![CDATA[Adjacency matrix]]></category>
		<category><![CDATA[Breadth-first search]]></category>
		<category><![CDATA[Dijkstra's algorithm]]></category>
		<category><![CDATA[Directed acyclic graph]]></category>
		<category><![CDATA[Graph]]></category>
		<category><![CDATA[graph algorithms]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[ineffective algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[time consuming algorithm]]></category>
		<category><![CDATA[Topological sorting]]></category>
		<category><![CDATA[Vertex]]></category>

		<guid isPermaLink="false">/?p=3494</guid>
		<description><![CDATA[Introduction We already know what’s topological sort of a directed acyclic graph. So why do we need a revision of this algorithm? First of all I never mentioned its complexity, thus to understand why we do need a revision let’s get again on the algorithm. We have a directed acyclic graph (DAG). There are no &#8230; <a href="/2012/12/10/computer-algorithms-topological-sort-revisited/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Topological Sort Revisited</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/10/01/computer-algorithms-topological-sort-of-a-graph/" rel="bookmark" title="Computer Algorithms: Topological Sort of a Graph">Computer Algorithms: Topological Sort of a Graph </a></li>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/08/31/computer-algorithms-graphs-and-their-representation/" rel="bookmark" title="Computer Algorithms: Graphs and their Representation">Computer Algorithms: Graphs and their Representation </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We already know what’s topological sort of a directed acyclic graph. So why do we need a revision of this algorithm? First of all I never mentioned its complexity, thus to understand why we do need a revision let’s get again on the algorithm.</p>
<p>We have a directed acyclic graph (DAG). There are no cycles so we must go for some kind of order putting all the vertices of the graph in such an order, that if there’s a directed edge (u, v), u must precede v in that order. </p>
<figure id="attachment_3506" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/1.-Topological-Sort.png"><img src="/wp-content/uploads/2012/12/1.-Topological-Sort.png" alt="Topological Sort" title="Topological Sort" width="620" height="399" class="size-full wp-image-3506" srcset="/wp-content/uploads/2012/12/1.-Topological-Sort.png 620w, /wp-content/uploads/2012/12/1.-Topological-Sort-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>The process of putting all the vertices of the DAG in such an order is called topological sorting. It’s commonly used in task scheduling or while finding the shortest paths in a DAG.</p>
<p>The algorithm itself is pretty simple to understand and code. We must start from the vertex (vertices) that don’t have predecessors. </p>
<p><figure id="attachment_3513" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/2.-Topological-Sort-step-1.png"><img src="/wp-content/uploads/2012/12/2.-Topological-Sort-step-1.png" alt="Topological Sort - step 1" title="Topological Sort - step 1" width="620" height="399" class="size-full wp-image-3513" srcset="/wp-content/uploads/2012/12/2.-Topological-Sort-step-1.png 620w, /wp-content/uploads/2012/12/2.-Topological-Sort-step-1-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure><span id="more-3494"></span></p>
<p>We put them in our sorted list in random order. Since they don’t depend on each other we can assume they are equally sorted already. Indeed thinking of a task schedule if there are tasks that don’t have predecessors (they don’t depend on other tasks before them) and that don’t depend on each other we can put them in random order (and execute them in random order).</p>
<figure id="attachment_3512" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/3.-Topological-Sort-Order.png"><img src="/wp-content/uploads/2012/12/3.-Topological-Sort-Order.png" alt="Topological Sort - Order" title="Topological Sort - Order" width="620" height="399" class="size-full wp-image-3512" srcset="/wp-content/uploads/2012/12/3.-Topological-Sort-Order.png 620w, /wp-content/uploads/2012/12/3.-Topological-Sort-Order-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Once we have the vertices with no predecessors we must remove the edges starting from them. Then – go again with the vertices with no predecessors. </p>
<figure id="attachment_3511" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/4.-Topological-Sort-step-2.png"><img src="/wp-content/uploads/2012/12/4.-Topological-Sort-step-2.png" alt="Topological Sort - step 2" title="Topological Sort - step 2" width="620" height="399" class="size-full wp-image-3511" srcset="/wp-content/uploads/2012/12/4.-Topological-Sort-step-2.png 620w, /wp-content/uploads/2012/12/4.-Topological-Sort-step-2-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>It’s as simple as that, so why do we need a revision of this algorithm? Well, basically because of its efficiency. </p>
<h2>Overview</h2>
<p>As we know most of the graph algorithms depend on the way the graph is represented in our application. We consider as the two main representations the adjacency matrix … </p>
<figure id="attachment_3510" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/5.-Adjacency-Matrix.png"><img src="/wp-content/uploads/2012/12/5.-Adjacency-Matrix.png" alt="Adjacency Matrix" title="Adjacency Matrix" width="620" height="399" class="size-full wp-image-3510" srcset="/wp-content/uploads/2012/12/5.-Adjacency-Matrix.png 620w, /wp-content/uploads/2012/12/5.-Adjacency-Matrix-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>… and adjacency lists.</p>
<figure id="attachment_3509" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/6.-Adjacency-Lists.png"><img src="/wp-content/uploads/2012/12/6.-Adjacency-Lists.png" alt="Adjacency Lists" title="Adjacency Lists" width="620" height="399" class="size-full wp-image-3509" srcset="/wp-content/uploads/2012/12/6.-Adjacency-Lists.png 620w, /wp-content/uploads/2012/12/6.-Adjacency-Lists-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>Let’s first take a look of some of the main approaches to get the topologically sorted list at the end of the algorithm. </p>
<p>What can we do in order to find the vertices with no predecessors? We can only scan the entire list of vertices. </p>
<h3>Adjacency Matrix</h3>
<p>In case we’re using adjacency matrix we need|V|^2 space to store the graph. To find the vertices with no predecessors we have to scan the entire graph, which will cost us O(|V|^2) time.  And we’ll have to do that |V| times. This will be |V|^3 time consuming algorithm and for dense graphs this will be quite an ineffective algorithm.</p>
<h3>Adjacency Lists</h3>
<p>What about the adjacency list? There we need |E| space to store a directed graph. How fast can we find a node with no predecessor? Practically we’ll need O(|E|) time.  Thus in the worst case we have again O(|V|^2) time consuming programs.</p>
<p>So what can be done in order to optimize this algorithm?</p>
<p>Practically we can start by picking up a random vertex and “go back” until we get a node with no predecessors. This approach can be very effective yet also very ineffective. First of all if we have to scan all the way back to a node with no predecessors this will cost us |V| time, but if we stuck on a node that don’t have a preceding node then we’ll have a constant speed.</p>
<p>This means that we can modify the algorithm a bit in order to improve a lot the algorithm. We just need to store both incoming and outgoing edges and slightly modify the adjacency lists.</p>
<figure id="attachment_3508" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists.png"><img src="/wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists.png" alt="Modified Adjacency Lists" title="Modified Adjacency Lists" width="620" height="399" class="size-full wp-image-3508" srcset="/wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists.png 620w, /wp-content/uploads/2012/12/7.-Modified-Adjacency-Lists-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>What’s the algorithm now?</p>
<p>First we easily find the nodes with no predecessors. Then, using a queue, we can keep the nodes with no predecessors and on each dequeue we can remove the edges from the node to all other nodes.</p>
<h2>Pseudo Code</h2>
<pre>
1. Represent the graph with two lists on each vertex (incoming edges and outgoing edges)
2. Make an empty queue Q;
3. Make an empty topologically sorted list T;
4. Push all items with no predecessors in Q;
5. While Q is not empty
   a. Dequeue from Q into u;
   b. Push u in T;
   c. Remove all outgoing edges from u;
6. Return T;
</pre>
<p>This approach will give us a better performance than the “brute force” approach. The running time complexity is O(|V| + |E|). The problem is that we need additional space and an operational queue, but this approach is a perfect example of how by using additional space you can get a better performing algorithm.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/10/01/computer-algorithms-topological-sort-of-a-graph/" rel="bookmark" title="Computer Algorithms: Topological Sort of a Graph">Computer Algorithms: Topological Sort of a Graph </a></li>
<li><a href="/2012/10/28/computer-algorithms-shortest-path-in-a-directed-acyclic-graph/" rel="bookmark" title="Computer Algorithms: Shortest Path in a Directed Acyclic Graph">Computer Algorithms: Shortest Path in a Directed Acyclic Graph </a></li>
<li><a href="/2012/09/10/computer-algorithms-graph-breadth-first-search/" rel="bookmark" title="Computer Algorithms: Graph Breadth First Search">Computer Algorithms: Graph Breadth First Search </a></li>
<li><a href="/2012/08/31/computer-algorithms-graphs-and-their-representation/" rel="bookmark" title="Computer Algorithms: Graphs and their Representation">Computer Algorithms: Graphs and their Representation </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/12/10/computer-algorithms-topological-sort-revisited/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Determine if a Number is Prime</title>
		<link>/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/</link>
		<comments>/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/#comments</comments>
		<pubDate>Tue, 08 May 2012 20:42:40 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[Eratosthenes]]></category>
		<category><![CDATA[ineffective algorithm]]></category>
		<category><![CDATA[Integer factorization algorithms]]></category>
		<category><![CDATA[Number]]></category>
		<category><![CDATA[Politics]]></category>
		<category><![CDATA[Primality tests]]></category>
		<category><![CDATA[Prime number]]></category>
		<category><![CDATA[Quadratic sieve]]></category>
		<category><![CDATA[Sieve of Atkin]]></category>
		<category><![CDATA[Sieve of Eratosthenes]]></category>

		<guid isPermaLink="false">/?p=3100</guid>
		<description><![CDATA[Introduction Each natural number that is divisible only by 1 and itself is prime. Prime numbers appear to be more interesting to humans than other numbers. Why is that and why prime numbers are more important than the numbers that are divisible by 2, for instance? Perhaps the answer is that prime numbers are largely &#8230; <a href="/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Determine if a Number is Prime</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/" rel="bookmark" title="Computer Algorithms: How to Determine the Day of the Week">Computer Algorithms: How to Determine the Day of the Week </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/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential 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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Each natural number that is divisible only by 1 and itself is prime. Prime numbers appear to be more interesting to humans than other numbers. Why is that and why prime numbers are more important than the numbers that are divisible by 2, for instance? Perhaps the answer is that prime numbers are largely used in cryptography, although they were interesting for the ancient Egyptians and Greeks (Euclid has proved that the prime numbers are infinite circa 300 BC). The problem is that there is not a formula that can tell us which is the next prime number, although there are algorithms that check whether a given natural number is prime. It&#8217;s very important these algorithms to be very effective, especially for big numbers.</p>
<h2>Overview</h2>
<p>As I said each natural number that is divisible only by 1 and itself is prime. That means that 2 is the first prime number and 1 is not considered prime. It’s easy to say that 2, 3, 5 and 7 are prime numbers, but what about 983? Well, yes 983 is prime, but how do we check that? If we want to know whether <strong>n</strong> is prime the very basic approach is to check every single number between 2 and n. It’s kind of a brute force.</p>
<h2>Implementation</h2>
<p>The basic implementation in PHP for the very basic (brute force) approach is as follows.</p>
<p><script src="https://gist.github.com/stoimen/640e6c0492d50904f3d6.js?file=prime_v1.php"></script></p>
<p>Unfortunately this is one very ineffective algorithm. We don’t have to check every single number between 1 and n, it’s enough to check only the numbers between 1 and n/2-1. If we find such a divisor that will be enough to say that <strong>n</strong> isn’t prime.</p>
<p><script src="https://gist.github.com/stoimen/640e6c0492d50904f3d6.js?file=prime_v2.php"></script></p>
<p>Although that code above optimizes a lot our first prime checker, it’s clear that for large numbers it won&#8217;t be very effective. Indeed checking against the interval [2, n/2 -1] isn’t the optimal solution. A better approach is to check against [2, sqrt(n)]. This is correct, because if <strong>n</strong> isn’t prime it can be represented as p*q = n. Of course if p > sqrt(n), which we assume can&#8217;t be true, that will mean that q &lt; sqrt(n).</p>
<p><script src="https://gist.github.com/stoimen/640e6c0492d50904f3d6.js?file=prime_v3.php"></script></p>
<p>Beside that these implementations shows how we can find prime number, they are a very good example of how an algorithm can be optimized a lot with some small changes.</p>
<h3>Sieve of Eratosthenes</h3>
<p>Although the sieve of Eratosthenes isn’t the exact same approach (to check whether a number is prime) it can give us a list of prime numbers quite easily. To remove numbers that aren’t prime, we start with 2 and we remove every single item from the list that is divisible by two. Then we check for the rest items of the list, as shown on the picture below.</p>
<p><img src="/wp-content/uploads/2012/05/SieveofEratosthenes.png" alt="/wp-content/uploads/2012/05/SieveofEratosthenes.png" /></p>
<p>The PHP implementation of the Eratosthenes sieve isn&#8217;t difficult.</p>
<p><script src="https://gist.github.com/stoimen/640e6c0492d50904f3d6.js?file=eratosthenes_sieve.php"></script></p>
<h2>Application</h2>
<p>As I said prime numbers are widely used in cryptography, so they are always of a greater interest in computer science. In fact every number can be represented by the product of two prime numbers and that fact is used in cryptography as well. That&#8217;s because if we know that number, which is usually very very big, it is still very difficult to find out what are its prime multipliers. Unfortunately the algorithms in this article are very basic and can be handy only if we work with small numbers or if our machines are tremendously powerful. Fortunately in practice there are more complex algorithms for finding prime numbers. Such are the sieves of Euler, Atkin and Sundaram.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/04/24/computer-algorithms-how-to-determine-the-day-of-the-week/" rel="bookmark" title="Computer Algorithms: How to Determine the Day of the Week">Computer Algorithms: How to Determine the Day of the Week </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/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential 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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/feed/</wfw:commentRss>
		<slash:comments>17</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>
