File tree Expand file tree Collapse file tree 2 files changed +63
-0
lines changed
Algorithms.NET/Searching/LinearSearch Expand file tree Collapse file tree 2 files changed +63
-0
lines changed Original file line number Diff line number Diff line change 1+ using BenchmarkDotNet . Attributes ;
2+ using System ;
3+ using System . Collections . Generic ;
4+ using System . Linq ;
5+ using System . Text ;
6+ using System . Threading . Tasks ;
7+
8+ namespace Algorithms . NET . Debug
9+ {
10+ [ MemoryDiagnoser ]
11+ public class SearchingBenchmark
12+ {
13+ private readonly List < int > _list = new ( ) ;
14+ private readonly List < double > _sortedList = new ( ) ;
15+ public SearchingBenchmark ( )
16+ {
17+ Random random = new ( ) ;
18+ for ( int i = 0 ; i <= 10000 ; i ++ )
19+ {
20+ _list . Add ( random . Next ( 1000 ) ) ;
21+ _sortedList . Add ( i ) ;
22+ }
23+ }
24+
25+ //Here we test the worst case scenario
26+
27+ [ Benchmark ]
28+ public void LinearSearch ( ) => Algorithms . NET . Searching . LinearSearch . LinearSearchAlgorithm . Search ( 10000 , _sortedList ) ;
29+
30+ [ Benchmark ]
31+ public void BinarySearchRecursive ( ) => Algorithms . NET . Searching . BinarySearch . BinarySearchAlgorithm . SearchRecursive ( 0 , _sortedList ) ;
32+
33+ [ Benchmark ]
34+ public void BinarySearchIterative ( ) => Algorithms . NET . Searching . BinarySearch . BinarySearchAlgorithm . SearchIterative ( 0 , _sortedList ) ;
35+ }
36+ }
Original file line number Diff line number Diff line change 1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . Text ;
4+
5+ namespace Algorithms . NET . Searching . LinearSearch
6+ {
7+ public class LinearSearchAlgorithm
8+ {
9+ /// <summary>
10+ /// Search an item in a list using linearSearch algorithm, Time complexity of O(n).
11+ /// </summary>
12+ /// <typeparam name="T">Type of items in list</typeparam>
13+ /// <param name="item">Item to search for.</param>
14+ /// <param name="list">List in which we want to search.</param>
15+ /// <returns>Index of item if found, Otherwise returns -1.</returns>
16+ public static int Search < T > ( T item , List < T > list ) where T : IComparable
17+ {
18+ for ( int i = 0 ; i < list . Count ; i ++ )
19+ {
20+ if ( list [ i ] . Equals ( item ) )
21+ return i ;
22+ }
23+
24+ return - 1 ;
25+ }
26+ }
27+ }
You can’t perform that action at this time.
0 commit comments