<?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>Linear search &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/linear-search/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: Insertion Sort</title>
		<link>/2012/02/13/computer-algorithms-insertion-sort/</link>
		<comments>/2012/02/13/computer-algorithms-insertion-sort/#comments</comments>
		<pubDate>Mon, 13 Feb 2012 14:21:57 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Application This algorithm]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Insertion sort]]></category>
		<category><![CDATA[Linear search]]></category>
		<category><![CDATA[Merge sort]]></category>
		<category><![CDATA[player]]></category>
		<category><![CDATA[Quicksort]]></category>
		<category><![CDATA[Selection sort]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sorting algorithms]]></category>
		<category><![CDATA[Strand sort]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[therefore sorting algorithms]]></category>
		<category><![CDATA[typical algorithm]]></category>

		<guid isPermaLink="false">/?p=2711</guid>
		<description><![CDATA[Overview Sorted data can dramatically change the speed of our program, therefore sorting algorithms are something quite special in computer science. For instance searching in a sorted list is faster than searching in an unordered list. There are two main approaches in sorting &#8211; by comparing the elements and without comparing them. A typical algorithm &#8230; <a href="/2012/02/13/computer-algorithms-insertion-sort/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Insertion Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </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>Overview</h2>
<p>Sorted data can dramatically change the speed of our program, therefore sorting algorithms are something quite special in computer science. For instance searching in a sorted list is faster than searching in an unordered list.</p>
<p>There are two main approaches in sorting &#8211; by comparing the elements and without comparing them. A typical algorithm from the first group is insertion sort. This algorithm is very simple and very intuitive to implement, but unfortunately it is not so effective compared to other sorting algorithms as <a href="/2010/06/18/friday-algorithms-iterative-quicksort/" title="Friday Algorithms: Iterative Quicksort">quicksort</a> and merge sort. Indeed insertion sort is useful for small sets of data with no more than about 20 items.</p>
<p>Insertion sort it is very intuitive method of sorting items and we often use it when we play card games. In this case the player often gets an unordered set of playing cards and intuitively starts to sort it. First by taking a card, making some comparisons and then putting the card on the right position.</p>
<p>So let’s say we have an array of data. In the first step the array is unordered, but we can say that it consists of two sub-sets: sorted and unordered, where on the first step the only item in the sorted sub-set is its first item. If the length of the array is n the algorithm is considered completed in n-1 steps. On each step our sorted subset is growing with one item. The thing is that we take the first item from the unordered sub-set and with some comparisons we put it into its place in the sorted sub-set, like on the diagram bellow.</p>
<p><figure id="attachment_2719" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/InsertionSortPrinciple.png"><img src="/wp-content/uploads/2012/02/InsertionSortPrinciple.png" alt="Main principle of insertion sort" title="Principle of Insertion Sort" width="620" class="size-full wp-image-2719" srcset="/wp-content/uploads/2012/02/InsertionSortPrinciple.png 960w, /wp-content/uploads/2012/02/InsertionSortPrinciple-300x107.png 300w" sizes="(max-width: 960px) 100vw, 960px" /></a><figcaption class="wp-caption-text">Main principle of insertion sort.</figcaption></figure><br />
<span id="more-2711"></span><br />
The insertion itself is the tricky part. We can insert the item once we find an item with a smaller value or if we have reached the front of the array like on the diagram bellow.</p>
<figure id="attachment_2721" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/InsertionSort.png"><img src="/wp-content/uploads/2012/02/InsertionSort.png" alt="Insertion sort example" title="Insertion Sort" width="620" class="size-full wp-image-2721" srcset="/wp-content/uploads/2012/02/InsertionSort.png 727w, /wp-content/uploads/2012/02/InsertionSort-300x196.png 300w" sizes="(max-width: 727px) 100vw, 727px" /></a><figcaption class="wp-caption-text">Example of insertion sort</figcaption></figure>
<h2>Implementation</h2>
<p>Here’s a quick implementation of insertion sort in PHP. The good thing is that it is easy to implement, but there are bad news too &#8211; insertion sort is slow and it is ineffective for large data sets.</p>
<pre lang="PHP">
$data = array(4, 2, 4, 1, 2, 6, 8, 19, 3);

function insertion_sort(&$arr)
{
	$len = count($arr);
	
	for ($i = 1; $i < $len; $i++) {
		$tmp = $arr[$i];
		$j = $i;
		
		while (($j >= 0) && ($arr[$j-1] > $tmp)) {
			$arr[$j] = $arr[$j-1];
			$j--;
		}
		$arr[$j] = $tmp;
	}
}
</pre>
<p>We can improve this code a little by using a sentinel, just like the sequential search, in order to remove one of the comparisons.</p>
<pre lang="PHP">
$data = array(4, 2, 4, 1, 2, 6, 8, 19, 3);

function insertion_sort_sentinel(&$arr)
{
	$len = count($arr);
	array_unshift(&$arr, -1);
	
	for ($i = 1; $i < $len+1; $i++) {
		$tmp = $arr[$i];
		$j = $i;
		
		while ($arr[$j-1] > $tmp) {
			$arr[$j] = $arr[$j-1];
			$j--;
		}
		$arr[$j] = $tmp;
	}
	array_shift(&$arr); // remove the sentinel
}
</pre>
<p>Just because we use searching the right position in an ordered array we can use binary search in order to improve even more the algorithm above. Unfortunately this doesn’t improve so much the general efficiency of this algorithm.</p>
<h2>Complexity</h2>
<p>As I said this algorithm is not so effective. Its complexity is O(n<sup>2</sup>) which is far worse than the O(n*log(n)) of quicksort, as you can see on the diagram bellow. </p>
<figure id="attachment_2723" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/02/InsertionSortComplexityChart.png"><img src="/wp-content/uploads/2012/02/InsertionSortComplexityChart.png" alt="n*n vs. n*log(n)" title="Insertion Sort Complexity Chart" width="600" height="371" class="size-full wp-image-2723" srcset="/wp-content/uploads/2012/02/InsertionSortComplexityChart.png 600w, /wp-content/uploads/2012/02/InsertionSortComplexityChart-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">n*n vs. n*log(n)</figcaption></figure>
<h2>Application</h2>
<p>This algorithm is useful for small sets of data and even if it doesn&#8217;t look like the most effective sorting algorithm, insertion sort can be useful for some reasons. First of all it is easy to implement, but it also does not require additional memory and it can be fast if the data is almost nearly sorted, which is great.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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/19/computer-algorithms-radix-sort/" rel="bookmark" title="Computer Algorithms: Radix Sort">Computer Algorithms: Radix Sort </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/02/13/computer-algorithms-insertion-sort/feed/</wfw:commentRss>
		<slash:comments>3</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>Computer Algorithms: Sequential Search</title>
		<link>/2011/11/24/computer-algorithms-sequential-search/</link>
		<comments>/2011/11/24/computer-algorithms-sequential-search/#comments</comments>
		<pubDate>Thu, 24 Nov 2011 09:25:35 +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[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[consecutive search]]></category>
		<category><![CDATA[forward sequential search]]></category>
		<category><![CDATA[Index]]></category>
		<category><![CDATA[ineffective searching algorithm]]></category>
		<category><![CDATA[ineffective searching algorithms]]></category>
		<category><![CDATA[Linear search]]></category>
		<category><![CDATA[linear search algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[reverse linear search approach]]></category>
		<category><![CDATA[search algorithm]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[sequential search]]></category>

		<guid isPermaLink="false">/?p=2483</guid>
		<description><![CDATA[Overview This is the easiest to implement and the most frequently used search algorithm in practice. Unfortunately the sequential search is also the most ineffective searching algorithm. However, it is so commonly used that it is appropriate to consider several ways to optimize it. In general the sequential search, also called linear search, is the &#8230; <a href="/2011/11/24/computer-algorithms-sequential-search/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Sequential Search</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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>
<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>This is the easiest to implement and the most frequently used search algorithm in practice. Unfortunately the sequential search is also the most ineffective searching algorithm. However, it is so commonly used that it is appropriate to consider several ways to optimize it. In general the sequential search, also called linear search, is the method of consecutively check every value in a list until we find the desired one.</p>
<h2>Basic Implementation</h2>
<p>The most natural approach is to loop through the list until we find the desired value. Here’s an implementation on PHP using FOR loop, something that can be easily written into any other computer language.</p>
<p><script src="https://gist.github.com/stoimen/cdc433af43d3f396fd2b.js"></script></p>
<p>This is really the most ineffective implementation. There are two big mistakes in this code. First of all we calculate the length of the list on every iteration of the array, and secondly after we find the desired element, we don’t break the loop, but continue to loop through the array.</p>
<p><img src="/wp-content/uploads/2011/11/forward-linear-search.jpg" alt="Forward Linear Search" /></p>
<p>Yes, if the element is repeated without the “break” we can find its last occurrence, but if not the loop will iterate over the end of the array with no practical value.</p>
<h3>Optimization of the forward sequential search</h3>
<p><script src="https://gist.github.com/stoimen/94ec4473ac050fb0fedf.js"></script></p>
<p>&#8230; and javascript:</p>
<p><script src="https://gist.github.com/stoimen/21f1496da3488e2c8c9c.js"></script></p>
<p><img src="/wp-content/uploads/2011/11/optimized-forward-linear-search.jpg" alt="Optimized forward linear search" /></p>
<p>Even with this little optimization the algorithm remains ineffective. As we can see, on every iteration we have two conditional expressions. First we check whether we’ve reached the end of the list, and then we check whether the current element equals to the searched element. So the question is can we reduce the number of the conditional expressions?</p>
<h2>Searching in reverse order</h2>
<p>Yes, we can reduce the number of comparison instructions from the forward approach of the linear search algorithm by using reverse order searching. Although it seems to be pretty much the same by reversing the order of the search we can discard one of the conditional expressions.</p>
<p><script src="https://gist.github.com/stoimen/02c44ea1d8238d5f39dc.js?file=sequential_search_reverse.php"></script></p>
<p><em>Note that we need to adjust index because of $index—expression.</em></p>
<p>Indeed here we have only one conditional expression, but the problem is that this implementation is correct ONLY when the element exists in the list, which is not always true. If the element doesn’t appears into the list, then this code can lead to an infinite loop. OK, but how can we stop the loop even when the list doesn’t contain the desired value? The answer is, by adding the searched value to the list.</p>
<h2>Sentinel</h2>
<p>The above problem can be solved by inserting the desired item as a sentinel value. Thus we’re sure that the list contains the value, so the loop will stop for sure even if at the beginning the value didn’t appear to be part of the list.</p>
<p><img src="/wp-content/uploads/2011/11/sentinel-linear-search.jpg" alt="Using setinel in sequential search" /></p>
<p><script src="https://gist.github.com/stoimen/02c44ea1d8238d5f39dc.js?file=sequential_search_sentinel.php"></script></p>
<p>This approach can be used to overcome the problem of the reverse linear search approach from the previous section.</p>
<h2>Complexity</h2>
<p>As I said at the beginning of this post this is one of the most ineffective searching algorithms. Of course the best case is when the searched value is at the very beginning of the list. Thus on the first comparison we can find it. On the other hand the worst case is when the element is located at the very end of the list. Assuming that we don’t know where the element is and the possibility to be anywhere in the list is absolutely equal, then the complexity of this algorithm is O(n).</p>
<h3>Different cases</h3>
<p>We must remember, however, that the algorithm’s complexity can vary depending on whether the element occurs once.</p>
<h3>Is it so ineffective?</h3>
<p>Sequential search can be very slow compared to binary search on an ordered list. But actually this is not quite true. <strong>Sequential search can be faster than binary search</strong> for small arrays, but it is assumed that for n &lt; 8 the sequential search is faster.</p>
<h2>Application</h2>
<p>The linear search is really very simple to implement and most web developers go to the forward implementation, which is the most ineffective one. On the other hand this algorithm is quite useful when we search in an unordered list. Yes, searching in an ordered list is something that can dramatically change the search algorithm. Actually searching and sorting algorithms are often used together.</p>
<p>A typical case is pulling something from a database, usually in form of a list and then search for some value in it. Unfortunately in most of the cases the database orders the returned result set and yet most of the developers perform a consecutive search over the list. Yet again when the list is ordered it is better to use binary search instead of sequential search.<br />
Let’s say we have a CSV file containing the usernames and the names of our users.</p>
<pre><code>Username,Name
jamesbond007,James Bond
jsmith,John Smith
...
</code></pre>
<p>Now we fetch these values into an array.</p>
<pre><code>// work case
$arr = array(
    array('name' =&amp;gt; 'James Bond', 'username' =&amp;gt; 'jamesbond007'),
    array('name' =&amp;gt; 'John Smith', 'username' =&amp;gt; 'jsmith')
);
</code></pre>
<p>Now using sequential search &#8230;</p>
<pre><code>// using a sentinel
$x = 'jsmith';
$arr[] = array('username' =&amp;gt; $x, 'name' =&amp;gt; '');
$index = 0;

while ($arr[$index++]['username'] != $x);

if ($index &amp;lt; count($arr)) {
    echo "Hello, {$arr[$index-1]['name']}";
} else {
    echo "Hi, guest!";
}
</code></pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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>
<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/11/24/computer-algorithms-sequential-search/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
