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;
}
}
}
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
Post a Comment