{"id":110,"date":"2012-07-05T16:17:16","date_gmt":"2012-07-05T14:17:16","guid":{"rendered":"http:\/\/codingexplained.com\/?p=110"},"modified":"2017-06-11T19:42:41","modified_gmt":"2017-06-11T17:42:41","slug":"linear-search-algorithm","status":"publish","type":"post","link":"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm","title":{"rendered":"Linear Search Algorithm"},"content":{"rendered":"<p>In programming, there are many ways in which to find an element in a given data structure, such as an array or list. For simplicity, we will use an array in the examples in this article. The easiest search algorithms are what we refer to as a linear or sequential searches. As the name indicates, these algorithms look at the elements sequentially, or one after another, in the order in which they appear in the data structure. Such algorithms can be implemented in several ways such as by using foreach, while or for loops.<\/p>\n<p>Below I give you examples of how to find an element in an array with the before mentioned approaches. We will return true if the element exists, but it is also common to return the index of the element (-1 if not found). The examples are written in PHP, but the syntax is very straightforward, even if you are not familiar with the language. Rewriting the examples to work in languages such as Java or C# is very simple.<\/p>\n<pre><code class=\"php\">function find1(array $myArray, $elementToFind) {\r\n\tforeach ($myArray as $element) {\r\n\t\tif ($element === $elementToFind) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\t\r\n\t\treturn false;\r\n\t}\r\n}<\/code><\/pre>\n<p>In the example above, we have implemented the algorithm by using a foreach loop. As the name of the loop implies, all elements in our data collection are looped through &#8211; unless we specify otherwise, that is. In this case, we are returning true if the current element is the one we are looking for, which terminates the loop immediately and ignores any remaining code in the function. Each element in the array is referenced as <span class=\"code\">$element<\/span> within the scope of the foreach loop (within the curly brackets, <a href=\"http:\/\/php.net\/manual\/en\/control-structures.foreach.php\" title=\"PHP foreach documentation\" target=\"_blank\">except for the last iteration<\/a>). This variable will reference elements at different indexes for every iteration, in the order in which elements appear in the array. If the element does not exist in the array, the loop is terminated after checking all of the elements, and then false is returned as per the last statement.<\/p>\n<pre><code class=\"php\">function find2(array $myArray, $elementToFind) {\r\n\t$i = 0;\r\n\t$count = count($myArray);\r\n\r\n\twhile ($i &lt; $count) {\r\n\t\tif ($myArray[$i] === $elementToFind) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\t\t\t\r\n\t\t$i++;\r\n\t}\r\n\t\t\r\n\treturn false;\r\n}<\/code><\/pre>\n<p>In the above example, we use the while loop to accomplish our task. This kind of loop will continue executing the code within the curly brackets while the condition in parenthesis is true. Once the condition evaluates to false, the loop terminates. However, the loop does not terminate immediately, but only after the code within the curly brackets has been executed. This is because the specified loop condition is evaluated <em>before<\/em> each iteration of the loop.<\/p>\n<p>With this approach, we are using an index counter <span class=\"code\">$i<\/span> to iterate through the array, hence why we check the element at position <span class=\"code\">$i<\/span> in <span class=\"code\">$myArray<\/span> instead of <span class=\"code\">$element<\/span> as in the previous example. We could assign the current element to a variable and then use it in our if statement if we wanted; to some, this is more readable, but it also adds an additional instruction to our algorithm. However, the latter is of little importance performance wise as we shall see later in this article. Here we keep looping while <span class=\"code\">$i<\/span> is less than the count of elements in the array, because if the function has not returned yet, then we should check more elements. We are using the less than operator and not less than or equal to because indexes start from zero and not one, which most people would find logical at first.<\/p>\n<pre><code class=\"php\">function find3(array $myArray, $elementToFind) {\r\n\t$count = count($myArray);\r\n\r\n\tfor ($i = 0; $i &lt; $count; $i++) {\r\n\t\tif ($myArray[$i] === $elementToFind) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\t\t\r\n\treturn false;\r\n}<\/code><\/pre>\n<p>For the last example, we have used the for loop, which consists of initialization, a loop condition and a statement to be executed after each iteration. These expressions are separated by semicolons. Usually a for loop will be of the form as seen in our example, but the for loop is in fact quite flexible. The expressions can be empty and can even contain several expressions. For more information about the for loop, we refer you to the <a href=\"http:\/\/php.net\/manual\/en\/control-structures.for.php\" title=\"PHP for loop documentation\" target=\"_blank\">PHP documentation<\/a>. As you might have noticed, this approach looks much like the second example with the while loop. First we initialize the variable <span class=\"code\">$i<\/span> to 0 and increment it by one after each iteration. The loop condition is checked before each iteration. Like with the while loop, it is this condition that determines if and when the loop should terminate. The rest of the algorithm is the same as we saw in the previous example.<\/p>\n<p>Please note that there are many variations of these linear or sequential search algorithms, but the main concept is the same.<\/p>\n<h3>Efficiency<\/h3>\n<p>One thing these algorithms have in common is that they are often very inefficient. They are certainly effective for small data collections, but the amount of data usually grows with time. Furthermore, such an algorithm can be used in many different scenarios, hence why it can be very hard to predict how much data the algorithm will handle ahead of time.<\/p>\n<p>What if the element we are searching for is the last element in the list? In this case, we would have to search through all of the other elements before finally reaching the element we are looking for (because we cannot know that the element is the last one). This may not be a problem if we are to search through 10 or 50 elements, but it is an entirely different story if the number is five million. On average, we would have to search through 2.5 million elements every time, with a worst case scenario of all five million. As you might suspect, this is not efficient.<\/p>\n<p>In the <a href=\"http:\/\/en.wikipedia.org\/wiki\/Big_o_notation\" title=\"Big O notation on Wikipedia\" target=\"_blank\">Big O notation<\/a>, the efficiency of this type of algorithm belongs to the <em>linear<\/em> class, which is noted as O(n).<\/p>\n<p>Luckily there are measures to improve performance, most noticeably by using a <a href=\"\/coding\/theory\/binary-search-algorithm\" title=\"Binary search algorithm\">binary search algorithm<\/a>. Such an algorithm does, however, require that the data collection is sorted, which is not without cost. These algorithms are furthermore slightly more complicated to implement, but the performance gain can be drastic. This type of algorithm belongs to the <em>logarithmic<\/em> class in the Big O notation; O(log n).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A linear search is the simplest search algorithm in computer programming. In this article we discuss the various implementation of this search algorithm and we also discuss the main disadvantage of this search strategy.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"jetpack_post_was_ever_published":false,"jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false}}},"categories":[37],"tags":[47,46,48,45,49,40],"series":[],"jetpack_publicize_connections":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.4 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Linear Search Algorithm<\/title>\n<meta name=\"description\" content=\"A linear search is the simplest search algorithm in computer programming. In this article we discuss the implementation and disadvantages.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Linear Search Algorithm\" \/>\n<meta property=\"og:description\" content=\"A linear search is the simplest search algorithm in computer programming. In this article we discuss the implementation and disadvantages.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm\" \/>\n<meta property=\"og:site_name\" content=\"Coding Explained\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/codingexplained\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/codingexplained\" \/>\n<meta property=\"article:published_time\" content=\"2012-07-05T14:17:16+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2017-06-11T17:42:41+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/codingexplained.com\/wp-content\/uploads\/2015\/11\/codingexplained-fb-promote.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"444\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Bo Andersen\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@codingexplained\" \/>\n<meta name=\"twitter:site\" content=\"@codingexplained\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Bo Andersen\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm\",\"url\":\"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm\",\"name\":\"Linear Search Algorithm\",\"isPartOf\":{\"@id\":\"https:\/\/codingexplained.com\/#website\"},\"datePublished\":\"2012-07-05T14:17:16+00:00\",\"dateModified\":\"2017-06-11T17:42:41+00:00\",\"author\":{\"@id\":\"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d\"},\"description\":\"A linear search is the simplest search algorithm in computer programming. In this article we discuss the implementation and disadvantages.\",\"breadcrumb\":{\"@id\":\"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/codingexplained.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Linear Search Algorithm\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/codingexplained.com\/#website\",\"url\":\"https:\/\/codingexplained.com\/\",\"name\":\"Coding Explained\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/codingexplained.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d\",\"name\":\"Bo Andersen\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/codingexplained.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g\",\"caption\":\"Bo Andersen\"},\"description\":\"I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!\",\"sameAs\":[\"https:\/\/codingexplained.com\",\"https:\/\/www.facebook.com\/codingexplained\",\"https:\/\/www.linkedin.com\/in\/ba0708\",\"https:\/\/twitter.com\/codingexplained\",\"https:\/\/www.youtube.com\/c\/codingexplained\"],\"url\":\"https:\/\/codingexplained.com\/author\/andy\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Linear Search Algorithm","description":"A linear search is the simplest search algorithm in computer programming. In this article we discuss the implementation and disadvantages.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm","og_locale":"en_US","og_type":"article","og_title":"Linear Search Algorithm","og_description":"A linear search is the simplest search algorithm in computer programming. In this article we discuss the implementation and disadvantages.","og_url":"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm","og_site_name":"Coding Explained","article_publisher":"https:\/\/www.facebook.com\/codingexplained","article_author":"https:\/\/www.facebook.com\/codingexplained","article_published_time":"2012-07-05T14:17:16+00:00","article_modified_time":"2017-06-11T17:42:41+00:00","og_image":[{"width":1200,"height":444,"url":"https:\/\/codingexplained.com\/wp-content\/uploads\/2015\/11\/codingexplained-fb-promote.png","type":"image\/png"}],"author":"Bo Andersen","twitter_card":"summary_large_image","twitter_creator":"@codingexplained","twitter_site":"@codingexplained","twitter_misc":{"Written by":"Bo Andersen","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm","url":"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm","name":"Linear Search Algorithm","isPartOf":{"@id":"https:\/\/codingexplained.com\/#website"},"datePublished":"2012-07-05T14:17:16+00:00","dateModified":"2017-06-11T17:42:41+00:00","author":{"@id":"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d"},"description":"A linear search is the simplest search algorithm in computer programming. In this article we discuss the implementation and disadvantages.","breadcrumb":{"@id":"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/codingexplained.com\/coding\/theory\/linear-search-algorithm#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/codingexplained.com\/"},{"@type":"ListItem","position":2,"name":"Linear Search Algorithm"}]},{"@type":"WebSite","@id":"https:\/\/codingexplained.com\/#website","url":"https:\/\/codingexplained.com\/","name":"Coding Explained","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/codingexplained.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/codingexplained.com\/#\/schema\/person\/e19c92ec991f571605f047cefeaa950d","name":"Bo Andersen","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/codingexplained.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/28f5826f9d5d544b0c5e1ec321dfdfb8?s=96&d=mm&r=g","caption":"Bo Andersen"},"description":"I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!","sameAs":["https:\/\/codingexplained.com","https:\/\/www.facebook.com\/codingexplained","https:\/\/www.linkedin.com\/in\/ba0708","https:\/\/twitter.com\/codingexplained","https:\/\/www.youtube.com\/c\/codingexplained"],"url":"https:\/\/codingexplained.com\/author\/andy"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p3mJkW-1M","_links":{"self":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts\/110"}],"collection":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/comments?post=110"}],"version-history":[{"count":19,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts\/110\/revisions"}],"predecessor-version":[{"id":2935,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/posts\/110\/revisions\/2935"}],"wp:attachment":[{"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/media?parent=110"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/categories?post=110"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/tags?post=110"},{"taxonomy":"series","embeddable":true,"href":"https:\/\/codingexplained.com\/wp-json\/wp\/v2\/series?post=110"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}