Skip to main content

Linear Search

Because Linear Search is so simple, I thought of doing something a bit different, so this post includes code in F# as well as C#.

F#

//linear search, but with error handling for 'value not found'
let LinearSearch num arr = 
    try
        arr |> List.findIndex (fun x -> x = num)
    with
        | :? System.Collections.Generic.KeyNotFoundException -> -1

//create array to use
let baseList = [3; 1; 7; 2; 9; 4; 1; 12; 25; 10; 11; 19; 22]

//two examples, one that works, and one that returns an error of -1
let resultFound = LinearSearch 12 baseList
let resultMissing = LinearSearch 23 baseList

C#

Code

using System;

namespace Algorithms
{
    class LinearSearch
    {
        public LinearSearch()
        {
        }
        
        public int Search(int num, int[] arrayToSearch)
        {
            //creates array
            //int[] arrayToSort = { 11, 7, 22, 2, 33, 3, 17, 44, 4, 55, 5, 66, 6, 1, 77 };

            int posFound = -1;
            for(int pos = 0; pos<arrayToSearch.Length; pos++)
            { 
                if (arrayToSearch[pos] == num)
                {
                    posFound = pos;
                    break;
                }
            }
            return posFound;
        }
    }
}

Usage

This returns position 9:

            LinearSearch search = new LinearSearch();
            int[] arr = { 11, 7, 22, 2, 33, 3, 17, 44, 4, 55, 5, 66, 6, 1, 77 };
            int result = search.Search(55, arr);




Comments

Popular posts from this blog

Heap Sort

Heap Sort is interesting because the use of the 'heapify' method that creates a binary tree as a flat array. First, a binary tree, also known as a heap, is created, and then the same function is used to sort the elements. In a heap, the first node in the array at zero (0) is the top node of the binary tree. The next two (2) items are the two (2) subnodes of the top node, and so on. For each node at a position (positionIndex), its 2 subnodes are in the following positions:

int left = 2 * positionIndex + 1;int right = 2 *  positionIndex + 2;
The CommonMethods.Swap() function is a reusable class, since swapping values by position is a common action during these example sorts.

Class

using System;

namespace Algorithms
{
    class HeapSort
    {
        public int[]  Sort()
        {
            //creates array
            int[] arrayToSort = { 11, 1, 22, 2, 33, 3, 44, 4, 55, 5, 66, 6, 7, 77, 88 };

            //creates a heap
            BuildHeap(arrayToSort);

            //sorts a heap
         …

Binary Search

This is the basic divide-and-conquer algorithm, requiring a sorted array. This repeatedly halves the remaining positions to search, until the value is found, or it determines that the value cannot be found. As mentioned, it requires a presorted array, or if unsorted, requires it is sorted. The benefits accrue in instances where the array is sorted once, but searched many times.

On a hypothetical array of 100 items, a linear search has an average performances of O(n/2), or a search of half the positions, 50, to find the item. By comparison, the average performance of Binary Search is O(log n), which for 100 items translates into 4.6, a radically reduced number of iterations, but with greater requirements for logic and memory.

Done in both C#, as an iterative while loop, and F#, as a recursion.

C#
using System; namespace Algorithms { class BinarySearch { public BinarySearch() { } public int Search(int num, int[] arrayToSearch) { …

Bucket Sort

This following uses the divide-and-conquer method of resolution, by dividing the problem into smaller arrays, sorting each smaller array, then reinserting the subarrays back into the original array.  This is not a pure solution, in that it uses the .NET List, rather than a linked list struct.

using System;
using System.Collections;
using System.Collections.Generic;

namespace Algorithms
{
    class BucketSort
    {
        public int[] Sort()
        {   
            //creates arbitrary array
            int[] arrayToSort = { 11, 7, 22, 2, 33, 3, 17, 44, 4, 55, 5, 66, 6, 1, 77 };
            //create bucket using hash, x/10
            List<int>[] bucketList = CreateHashedArray(arrayToSort, 10);
            //sort the bucket list back into the original array
            ReorderList(bucketList, arrayToSort);
            return arrayToSort;
        }

        private int hashFunction(int num, int buckets)
        {
            return num / buckets;
        }

        private List<int>[] CreateHashed…