<?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>sorting algorithm &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/sorting-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: Sorting in Linear Time</title>
		<link>/2012/12/24/computer-algorithms-sorting-in-linear-time/</link>
		<comments>/2012/12/24/computer-algorithms-sorting-in-linear-time/#comments</comments>
		<pubDate>Mon, 24 Dec 2012 11:23:20 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Binary numeral system]]></category>
		<category><![CDATA[Bucket sort]]></category>
		<category><![CDATA[Combinatorics]]></category>
		<category><![CDATA[Counting sort]]></category>
		<category><![CDATA[faster sorting algorithm]]></category>
		<category><![CDATA[Integer sorting]]></category>
		<category><![CDATA[linear time sorting algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[numeric systems]]></category>
		<category><![CDATA[Order theory]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pigeonhole sort]]></category>
		<category><![CDATA[Radix sort]]></category>
		<category><![CDATA[radix sort algorithm]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[sorting algorithm]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[stable sort algorithm]]></category>
		<category><![CDATA[supporting stable sort algorithm]]></category>

		<guid isPermaLink="false">/?p=3516</guid>
		<description><![CDATA[Radix Sort The first question when we see the phrase “sorting in linear time” should be – where’s the catch? Indeed there’s a catch and the thing is that we can’t sort just anything in linear time. Most of the time we can speak on sorting integers in linear time, but as we can see &#8230; <a href="/2012/12/24/computer-algorithms-sorting-in-linear-time/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Sorting in Linear Time</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2013/01/02/computer-algorithms-bucket-sort/" rel="bookmark" title="Computer Algorithms: Bucket Sort">Computer Algorithms: Bucket Sort </a></li>
<li><a href="/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/" rel="bookmark" title="Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort!">Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort! </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2013/01/07/computer-algorithms-adding-large-integers/" rel="bookmark" title="Computer Algorithms: Adding Large Integers">Computer Algorithms: Adding Large Integers </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Radix Sort</h2>
<p>The first question when we see the phrase “sorting in linear time” should be – where’s the catch? Indeed there’s a catch and the thing is that we can’t sort just anything in linear time. Most of the time we can speak on sorting integers in linear time, but as we can see later this is not the only case. </p>
<p>Since we speak about integers, we can think of a faster sorting algorithm than usual. Such an algorithm is the counting sort, which can be very fast in some cases, but also very slow in others, so it can be used carefully. Another linear time sorting algorithm is radix sort.</p>
<h2>Introduction</h2>
<p>Count sort is absolutely brilliant and easy to implement. In case we sort integers in the range [n, m] on the first pass we just initialize a zero filled array with length m-n. Than on the second pass we “count” the occurrence of each integer. On the third pass we just sort the integers with an ease. </p>
<p><img src="https://docs.google.com/drawings/pub?id=1VOyJ9u_sp5YQB6gpt0bcWFOKjYTSugoQWJYRkFFZTLc&amp;w=620&amp;h=399"></p>
<p>However we have some problems with that algorithm. What if we have only few items to sort that are very far from each other like [2, 1, 10000000, 2]. This will result in a very large unused data. So we need a dense integer sequence. This is important because we must know in advance the nature of the sequence which is rarely sure.</p>
<p>That’s why we need to use another linear time sorting algorithm for integers that doesn’t have this disadvantage. Such an algorithm is the radix sort.</p>
<h2>Overview</h2>
<p>The idea behind the radix sort is simple. We must look at our “integer” sequence as a string sequence. OK, to become clearer let me give you an example. Our sequence is [12, 2, 23, 33, 22]. First we take the leftmost digit of each number. Thus we must compare [_2, 2, _3, _3, _2]. Clearly we can assume that since the second number “2” is only a one digit number we can fill it up with a leading “0”, to become 02 or _2 in our example: [_2, _2, _3, _3, _2]. Now we sort this sequence with a stable sort algorithm.</p>
<h3>What is a Stable Sort Algorithm</h3>
<p>A stable sort algorithm is an algorithm that sorts a list by preserving the positions of the elements in case they are equal. In terms of PHP this means that:</p>
<pre lang="PHP">
array(0 => 12, 1=> 13, 2 => 12); 
</pre>
<p>Will be sorted as follows:</p>
<pre lang="PHP">
array(0 => 12, 2 => 12, 1 => 13);
</pre>
<p>Thus the third element becomes second following the first element. Note that the third and the first element are equal, but the third appears later in the sequence so it remains later in the sorted sequence.</p>
<p>In the radix sort example, we need a stable sort algorithm, because we need to worry about only one position of digit we explore.</p>
<p>So what happens in our example after we sort the sequence? </p>
<p><img src="https://docs.google.com/drawings/pub?id=10dVPfCVf8YI2sEJNuAujnrOx0g0RxWGsQdTJ0xqGt1k&amp;w=620&amp;h=399"></p>
<p>As we can see we’re far from a sorted sequence, but what if we proceed with the next “position” &#8211; the decimal digit?</p>
<p>Than we end up with this:</p>
<p><img src="https://docs.google.com/drawings/pub?id=1oaKToHilxrKyGJzwm7NvmrSaL3uVRO3R7r0RCb0jrR4&amp;w=621&amp;h=264"></p>
<p>Now we have a sorted sequence, so let’s summarize the algorithm in a short pseudo code.</p>
<h2>Pseudo Code</h2>
<p>The simple approach behind the radix sort algorithm can be described as pseudo code, assuming that we’re sorting decimal integers.</p>
<p>1. For each digit at position 10^0 to 10^n<br />
   1.1. Sort the numbers by this digit using a stable sort algorithm; </p>
<p>The thing is that here we talk about decimal, but actually this algorithm can be applied equally on any numeric systems. That is why it’s called “radix” sort. </p>
<p>Thus we can sort binary numbers, hexadecimals etc.</p>
<p>It’s important to note that this algorithm can be also used to sort strings alphabetically.</p>
<pre>
[ABC, BBC, ABA, AC]
[__C, __C, __A, __C] => [ABA, ABC, BBC, AC]
[_B_, _B_, _B_, _A_] => [AC, ABA, ABC, BBC]
[___, A__, A__, B__] => [AC, ABA, ABC, BBC]
</pre>
<p>That is simply correct because we can assume that our alphabet is another 27 digit numeric system (in case of the Latin alphabet).</p>
<h2>Complexity</h2>
<p>As I said in the beginning radix sort is a linear time sorting algorithm. Let’s see why. First we depend on the numeric system. Let’s assume we have a decimal numeric system – then we have N passes sorting 10 digits which is simply 10*N. In case of K digit numeric system our algorithm will be O(K*N) which is linear.</p>
<p>However you must note that in case we sort N numbers in an N digit numeric system the complexity will become O(N^2)!</p>
<p>We must also remember that in order to implement radix sort and a supporting stable sort algorithm we need an extra space.</p>
<h2>Application</h2>
<p>Sorting integers can be faster than sorting just anything, so any time we need to implement a sorting algorithm we must carefully investigate the input data. And that’s also the big disadvantage of this algorithm – we must know the input in advance, which is rarely the case.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2013/01/02/computer-algorithms-bucket-sort/" rel="bookmark" title="Computer Algorithms: Bucket Sort">Computer Algorithms: Bucket Sort </a></li>
<li><a href="/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/" rel="bookmark" title="Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort!">Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort! </a></li>
<li><a href="/2012/03/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </a></li>
<li><a href="/2013/01/07/computer-algorithms-adding-large-integers/" rel="bookmark" title="Computer Algorithms: Adding Large Integers">Computer Algorithms: Adding Large Integers </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/12/24/computer-algorithms-sorting-in-linear-time/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Heap and Heapsort</title>
		<link>/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/</link>
		<comments>/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/#comments</comments>
		<pubDate>Tue, 07 Aug 2012 12:33:15 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[Binary heap]]></category>
		<category><![CDATA[Binary tree]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Discrete mathematics]]></category>
		<category><![CDATA[Heap]]></category>
		<category><![CDATA[Heapsort]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[next]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Priority queue]]></category>
		<category><![CDATA[purpose algorithm]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[sorting algorithm]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Tree]]></category>

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

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

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

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

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

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

		<guid isPermaLink="false">/?p=2521</guid>
		<description><![CDATA[Overview In my previous article I discussed how the sequential (linear) search can be used on an ordered lists, but then we were limited by the specific features of the given task. Obviously the sequential search on an ordered list is ineffective, because we consecutively check every one of its elements. Is there any way &#8230; <a href="/2011/12/12/computer-algorithms-jump-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Jump Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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>
<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/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>In <a title="Computer Algorithms: Linear Search in Sorted Lists" href="/2011/12/02/computer-algorithms-linear-search-in-sorted-lists/">my previous article</a> I discussed how the sequential (linear) search can be used on an ordered lists, but then we were limited by the specific features of the given task. Obviously the <a href="/2011/11/24/computer-algorithms-sequential-search/" title="Computer Algorithms: Sequential Search">sequential search</a> on an ordered list is ineffective, because we consecutively check every one of its elements. Is there any way we can optimize this approach? Well, because we know that the list is sorted we can check some of its items, but not all of them. Thus when an item is checked, if it is less than the desired value, we can skip some of the following items of the list by jumping ahead and then check again. Now if the checked element is greater than the desired value, we can be sure that the desired value is hiding somewhere between the previously checked element and the currently checked element. If not, again we can jump ahead. Of course a good approach is to use a fixed step. Let’s say the list length is n and the step’s length is k. Basically we check list(0), then list(k-1), list(2k-1) etc. Once we find the interval where the value might be (m*k-1 &lt; x &lt;= (m+1)*k &#8211; 1), we can perform a sequential search between the last two checked positions. By choosing this approach we avoid a lot the weaknesses of the sequential search algorithm. Many comparisons from the sequential search here are eliminated.</p>
<h2>How to choose the step&#8217;s length</h2>
<p>We know that it is a good practice to use a fixed size step. Actually when the step is 1, the algorithm is the traditional sequential search. The question is what should be the length of the step and is there any relation between the length of the list (n) and the length of the step (k)? Indeed there is such a relation and often you can see sources directly saying that the best length k = √n. Why is that?</p>
<p>Well, in the worst case, we do n/k jumps and if the last checked value is greater than the desired one, we do at most k-1 comparisons more. This means n/k + k &#8211; 1 comparisons. Now the question is for what values of k this function reaches its minimum. For those of you who remember maths classes this can be found with the formula -n/(k^2) + 1 = 0. Now it’s clear that for k = √n the minimum of the function is reached.</p>
<p>Of course you don’t need to prove this every time you use this algorithm. Instead you can directly assign √n to be the step length. However it is good to be familiar with this approach when trying to optimize an algorithm.</p>
<p>Let’s cosider the following list: (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610). Its length is 16. Jump search will find the value of 55 with the following steps.</p>
<figure id="attachment_2539" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/jump-search-fig-1.png"><img class="size-full wp-image-2539" title="jump-search-fig-1" src="/wp-content/uploads/2011/12/jump-search-fig-1.png" alt="Jump search basic implementation" width="620" srcset="/wp-content/uploads/2011/12/jump-search-fig-1.png 964w, /wp-content/uploads/2011/12/jump-search-fig-1-300x65.png 300w" sizes="(max-width: 964px) 100vw, 964px" /></a><figcaption class="wp-caption-text">Jump search skips some of the items of the list in order to improve performance!</figcaption></figure>
<h2>Implementation</h2>
<p>Let’s see an example of jump search, written in <a title="PHP on stoimen.com" href="/category/php/">PHP</a>.<span id="more-2521"></span></p>
<pre lang="PHP">
$list = array();

for ($i = 0; $i < 1000; $i++) {
	$list[] = $i;
}

// now we have a sorted list: (0, 1, 2, 3, ..., 999)

function jump_search($x, $list)
{
	// calculate the step
	$len = count($list);
	$step = floor(sqrt($len));
	$prev = 0;
	
	while ($list[($step < $len ? $step : $len)] < $x) {
		$prev = $step;
		$step += floor(sqrt($len));
		
		if ($step >= $len) {
			return FALSE;
		}
	}
	
	while ($list[$prev] < $x) {
		$prev++;
		if ($prev == ($step < $len ? $step : $len)) {
			return FALSE;
		}
	}
	
	if ($list[$prev] == $x) {
		return $prev;
	}
	
	return FALSE;
}

echo (int)jump_search(674, $list);
</pre>
<p>Here we have a sorted list with 1000 elements that looks like this: (0, 1, 2, ..., 999). Obviously with sequential search we'll find the value of 674 with exactly on the 674-th iteration. Here, with jump search we can reach it on the 44-th iteration, and this shows us the advantage of jump search over the sequential search on ordered lists.</p>
<h2>Further Optimization</h2>
<p>Although all examples here deal with small lists in practice this is not always true. Sometimes the step itself can be a very large number, so once you know the interval where the desired value could be you can perform jump search again.</p>
<p>We saw that the best size of the step is √n, but it is not a good idea to start from the first element of the list just as we didn’t in the example above. A better option is to begin from kth item. Now we can improve the above solution.</p>
<figure id="attachment_2542" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/jump-search-fig-2.png"><img class="size-full wp-image-2542" title="jump-search-fig-2" src="/wp-content/uploads/2011/12/jump-search-fig-2.png" alt="Basic jump search can be slightly optimized!" width="620" srcset="/wp-content/uploads/2011/12/jump-search-fig-2.png 964w, /wp-content/uploads/2011/12/jump-search-fig-2-300x65.png 300w" sizes="(max-width: 964px) 100vw, 964px" /></a><figcaption class="wp-caption-text">The basic implementation of jump search can be slightly optimized!</figcaption></figure>
<h2>Complexity</h2>
<p>Obviously the complexity of the algorithm is O(√n), but once we know the interval where the value is we can improve it by applying jump search again. Indeed let’s say the list length is 1,000,000. The jump interval should be: √1000000=1000. As you can see again, you can use jump search with a new step √1000≈31. Every time we find the desired interval we can apply the jump search algorithm with a smaller step. Of course finally the step will be 1. In this case the complexity of the algorithm is no longer O(√n). Now its complexity is approaching logarithmic value. The problem is that the implementation of this approach is considered to be more difficult than the binary search, where the complexity is also O(log(n)).</p>
<h2>Application</h2>
<p>As almost every algorithm the jump search is very convinient for a certain kind of tasks. Yes, the binary search is easy to implement and its complexity is O(log(n)), but in case of a very large list the direct jump to the middle can be a bad idea. Then we should make a large step back if the searched value is placed at the beginning of the list.</p>
<p>Perhaps every one of us has performed some sort of a primitive jump search in his life without even knowing it. Do you remember cassette recorders? We used the "fast forward" key and periodically checked whether the tape was on our favorite song. Once we stopped at the middle of the song we used the "rewind" button to find exactly the beginning of the song.</p>
<p>This clumsy example can give us the answer of where jump search can be better than binary search. The advantage of jump search is that you need to jump back only once (in case of the basic implementation).</p>
<figure id="attachment_2544" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/12/jump-search-fig-3.png"><img class="size-full wp-image-2544" title="jump-search-fig-3" src="/wp-content/uploads/2011/12/jump-search-fig-3.png" alt="Jump search is very useful when jumping back is significantly slower than jumping forward!" width="620" srcset="/wp-content/uploads/2011/12/jump-search-fig-3.png 964w, /wp-content/uploads/2011/12/jump-search-fig-3-300x65.png 300w" sizes="(max-width: 964px) 100vw, 964px" /></a><figcaption class="wp-caption-text">Jump search is very useful when jumping back is significantly slower than jumping forward!</figcaption></figure>
<p>If jumping back takes you significantly more time than jumping forward then you should use this algorithm.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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>
<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/02/computer-algorithms-linear-search-in-sorted-lists/" rel="bookmark" title="Computer Algorithms: Linear Search in Sorted Lists">Computer Algorithms: Linear Search in Sorted Lists </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/12/12/computer-algorithms-jump-search/feed/</wfw:commentRss>
		<slash:comments>3</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>
		<item>
		<title>Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort!</title>
		<link>/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/</link>
		<comments>/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 09:30:35 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[quicksort algorithm]]></category>
		<category><![CDATA[Selection algorithm]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[sorting algorithm]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Spreadsort]]></category>

		<guid isPermaLink="false">/?p=1689</guid>
		<description><![CDATA[Yes! It&#8217;s really really fast, and it&#8217;s far quicker than the quicksort algorithm, which is considered as the fastest sorting algorithm in practice. However how it&#8217;s possible to be faster than the quicksort, which is the fastest algorithm?! Is that true? Actually it&#8217;s true, but only in few cases. It works with integers, you&#8217;ve to &#8230; <a href="/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/" class="more-link">Continue reading <span class="screen-reader-text">Friday Algorithms: Sorting a Set of Integers &#8211; Far Quicker than Quicksort!</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
<li><a href="/2010/06/18/friday-algorithms-iterative-quicksort/" rel="bookmark" title="Friday Algorithms: Iterative Quicksort">Friday Algorithms: Iterative Quicksort </a></li>
<li><a href="/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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Yes! It&#8217;s really really fast, and it&#8217;s far quicker than the <a href="/2010/06/18/friday-algorithms-iterative-quicksort/">quicksort</a> algorithm, which is considered as the fastest sorting algorithm in practice. However how it&#8217;s possible to be faster than the quicksort, which is the fastest algorithm?! Is that true? Actually it&#8217;s true, but only in few cases. It works with integers, you&#8217;ve to know the first and the last element from that set and you&#8217;ve to be sure that every element is unique</p>
<p>Imagine you&#8217;ve a set of numbers all of them greater than 1 and lesser than 1000. Of course you&#8217;re not suppose to have all of the integers between 1 and 1000, but only few of them &#8211; think of 500 numbers between 1 and 1000! Here&#8217;s important to note &#8211; that this is only an example, you can have far more than only few numbers between 1 and 1000 &#8211; what about the numbers between 1 and 1,000,000 &#8211; this is a big set, isn&#8217;t it.</p>
<p>The question is &#8211; if there are so many constraints, why should I use that algorithm instead of quicksort, or another sorting algorithm, that works with everything. The answer is clear &#8211; yes, you&#8217;d prefer quicksort if you&#8217;ve to sort some arbitrary data, but when it comes to integers, and you&#8217;ve, let&#8217;s say, 1,000,000 integers, my advice is &#8211; use this algorithm!</p>
<h2>Sorting the Set</h2>
<h3>1. First Pass</h3>
<p>First we have an unsorted array, but we know the minimum and maximum of the set.</p>
<p><a href="/wp-content/uploads/2010/06/unsorted.png"><img class="aligncenter size-full wp-image-1701" title="unsorted" src="/wp-content/uploads/2010/06/unsorted.png" alt="an unsorted array of integers" width="283" height="111" /></a></p>
<p>On the first pass initialize an empty array with as many elements, as they are between the first and the last element of the set &#8211; for a set between 1 and 1000 &#8211; that will be an array with 1000 elements &#8211; each of which will be a zero in the beginning.</p>
<p><a href="/wp-content/uploads/2010/06/temp-array.png"><img class="aligncenter size-full wp-image-1700" title="temp-array" src="/wp-content/uploads/2010/06/temp-array.png" alt="temporary array with 0 on every element" width="277" height="138" /></a></p>
<p>Than loop trough the set and for every element in the set &#8211; you should put a 1 on it&#8217;s place</p>
<p><a href="/wp-content/uploads/2010/06/array-first-pass.png"><img class="aligncenter size-full wp-image-1699" title="array-first-pass" src="/wp-content/uploads/2010/06/array-first-pass.png" alt="sort a set - first pass" width="299" height="162" /></a></p>
<p>Now we have an array of 0 and 1.</p>
<h3>2. Second Pass</h3>
<p>After the first pass, you&#8217;d guess what you&#8217;ve to do &#8211; loop trough the second array and print the keys of the elements different from 0 &#8211; those that are 1.</p>
<p><a href="/wp-content/uploads/2010/06/sorted.png"><img class="aligncenter size-full wp-image-1698" title="sorted" src="/wp-content/uploads/2010/06/sorted.png" alt="a sorted set of integers" width="312" height="231" srcset="/wp-content/uploads/2010/06/sorted.png 312w, /wp-content/uploads/2010/06/sorted-300x222.png 300w" sizes="(max-width: 312px) 100vw, 312px" /></a></p>
<p>Now the array is sorted!</p>
<h2>Source Code</h2>
<pre lang="javascript">
var a = [34, 203, 3, 746, 200, 984, 198, 764];

function setSort(arr)
{
    var t = [], len = arr.length;
    for (var i = 0; i < 1000; i++) {
        t[i] = 0;
    }

    for (i = 0; i < len; i++) {
        t[arr[i]] = 1;
    }

    for (i = 0; i < 1000; i++) {
        if (1 == t[i]) {
            console.log(i);
        }
    }
}

setSort(a);
</pre>
<p>Now that you've seen that algorithm, perhaps you'd guess that it's no so difficult to change from integers to any other set, and once again I should say that in many cases this is the best algorithm for sorting! Very often quicksort is preferred, but not always there isn't something faster!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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/03/13/computer-algorithms-quicksort/" rel="bookmark" title="Computer Algorithms: Quicksort">Computer Algorithms: Quicksort </a></li>
<li><a href="/2010/06/18/friday-algorithms-iterative-quicksort/" rel="bookmark" title="Friday Algorithms: Iterative Quicksort">Friday Algorithms: Iterative Quicksort </a></li>
<li><a href="/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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/06/25/friday-algorithms-sorting-a-set-of-integers-far-quicker-than-quicksort/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>
