Example #1
0
        public void BinarySearch()
        {
            var array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            var ret = new BinarySearch().Find(array, 0, array.Length - 1, 2);

            Assert.AreEqual(true, ret);
        }
Example #2
0
        static protected bool TryFindUniqueCoreInt(TElement[] indexArray, Func <TElement, int> keySelector, IComparer <int> _, int key, out TElement result)
        {
            var index = BinarySearch.FindFirstIntKey(indexArray, key, keySelector);

            if (index != -1)
            {
                result = indexArray[index];
                return(true);
            }
            else
            {
                result = default;
                return(false);
            }
        }
        public void BinarySearch_Array_Contains_5_Elemnts_and_Target_is_NOT_In_left_part()
        {
            BinarySearch bSObj          = new BinarySearch(new int[] { 2, 17, 42, 51, 60 });
            int          target         = 4;
            int          expectedResult = -1;

            while (bSObj.GetResult() != -1)
            {
                bSObj.Step(target);
                Console.WriteLine(bSObj.GetResult());
            }
            int result = bSObj.GetResult();

            Assert.AreEqual(expectedResult, result);
        }
Example #4
0
    public int?GetKthSmallest(int k)
    {
        int?indexOfKthSmallest = BinarySearch.Search(
            start: 0,
            end: _orderedValues.Length - 1,
            // Querying the BIT from 0 to an end index counts the number of inserted values that
            // are <= to the value at the end index (in the ordered values array). The kth smallest
            // value is at the index that makes the BIT query == k. We binary search to find it.
            verifier: queryEndIndex => _insertionBIT.SumQuery(queryEndIndex) >= k,
            mode: BinarySearch.Mode.FalseToTrue);

        return(indexOfKthSmallest.HasValue
            ? _orderedValues[indexOfKthSmallest.Value]
            : (int?)null);
    }
Example #5
0
        public void TestMethod5()
        {
            //Arrage
            BinarySearch a = new BinarySearch();

            int[] nums     = new int[] { 1, 2, 3 };
            int   expected = 2;

            //Act
            var actual = a.FindPeakElement(nums);

            //Assert
            //Assert.AreEqual(expected.Length, actual.Length);
            Assert.AreEqual(expected, actual);
        }
        public void BinarySearch_Array_Contains_5_Elemnts_and_Target_is_Last_In_Array_on_the_right()
        {
            BinarySearch bSObj          = new BinarySearch(new int[] { 2, 17, 42, 51, 60 });
            int          target         = 60;
            int          expectedResult = 1;

            while (bSObj.GetResult() != 1)
            {
                bSObj.Step(target);
                Console.WriteLine(bSObj.GetResult());
            }
            int result = bSObj.GetResult();

            Assert.AreEqual(expectedResult, result);
        }
        public void BinarySearch_Array_Contains_10Elemnts_and_Target_is_NOT_In_left_part()
        {
            BinarySearch bSObj          = new BinarySearch(new int[] { 0, 2, 4, 8, 10, 12, 14, 16, 18, 20 });
            int          target         = 5;
            int          expectedResult = -1;

            while (bSObj.GetResult() != -1)
            {
                bSObj.Step(target);
                Console.WriteLine(bSObj.GetResult());
            }
            int result = bSObj.GetResult();

            Assert.AreEqual(expectedResult, result);
        }
Example #8
0
        // Unique

        static protected TElement FindUniqueCore <TKey>(TElement[] indexArray, Func <TElement, TKey> keySelector, IComparer <TKey> comparer, TKey key, bool throwIfNotFound = true)
        {
            var index = BinarySearch.FindFirst(indexArray, key, keySelector, comparer);

            if (index != -1)
            {
                return(indexArray[index]);
            }
            else
            {
                if (throwIfNotFound)
                {
                    ThrowKeyNotFound(key);
                }
                return(default);
Example #9
0
        public static void BinarySearchCase()
        {
            Console.WriteLine("********************Binary Search*************************");
            string filePath = $@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)}";

            Console.WriteLine("Enter the sorted array string :");
            string test = Console.ReadLine();

            int[] input = JsonConvert.DeserializeObject <int[]>(test);
            Console.WriteLine("Enter the Search Value:");
            int value = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine(BinarySearch.IterativeSearch(input, 0, input.Length, value));
            Console.WriteLine(BinarySearch.count);
        }
Example #10
0
        static protected bool TryFindUniqueCore <TKey>(TElement[] indexArray, Func <TElement, TKey> keySelector, IComparer <TKey> comparer, TKey key, out TElement result)
        {
            var index = BinarySearch.FindFirst(indexArray, key, keySelector, comparer);

            if (index != -1)
            {
                result = indexArray[index];
                return(true);
            }
            else
            {
                result = default;
                return(false);
            }
        }
Example #11
0
        public void ConstructorTest1()
        {
            Func <int, double> function = x => elements[x];
            BinarySearch       search   = new BinarySearch(function, 0, elements.Length);

            int a1 = search.FindRoot();

            Assert.AreEqual(1, a1);

            for (int i = 0; i < elements.Length; i++)
            {
                int a2 = search.Find(elements[i]);
                Assert.AreEqual(i, a2);
            }
        }
Example #12
0
    public void TestSearch()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        // checking a number that is in the array
        Assert.True(BinarySearch.Search(numbers, 4));

        // checking boundaries
        Assert.True(BinarySearch.Search(numbers, 1));
        Assert.True(BinarySearch.Search(numbers, 5));

        // checking numbers that are not in the array
        Assert.False(BinarySearch.Search(numbers, 6));
        Assert.False(BinarySearch.Search(numbers, 0));
    }
        public void SearchIterative(int[] data)
        {
            object result = 0;

            _stopWatch.Start();
            result = BinarySearch.SearchIterative(data, 8);
            _stopWatch.Stop();

            Logger.WriteLine($"**********************************************************************");
            Logger.WriteLine($"BinarySearch | iterative | index: {JsonSerializer.Serialize(result)}");
            Logger.WriteLine($"Elapsed Time: {_stopWatch.Elapsed.ToString()}");
            Logger.WriteLine($"**********************************************************************");

            Assert.IsTrue(int.TryParse(JsonSerializer.Serialize(result), out int num));
        } // end method
        static void BinarySearchExample04()
        {
            var array = new[]
            {
                Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()
            }.OrderBy(a => a).Select(a => a.ToString()).ToArray();

            int?indexExpected = null;

            Console.WriteLine($@"Expected index: {(indexExpected.HasValue ? indexExpected.Value.ToString() : "null")}");

            var index       = BinarySearch.IndexOf(array, "serge");
            var indexString = index.HasValue ? index.Value.ToString() : "null";

            Console.WriteLine($"Actual index: {indexString}");
        }
Example #15
0
        public static void Main(string[] args)
        {
            int[] arr  = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int   item = 2;
            var   res  = BinarySearch.BinarySearcher(arr, item);

            Console.WriteLine("result! {0}", res);



            var list = new List <int> {
                3, 5, 2, 1, 4, 7, 9, 6, 8
            };

            var resSort = SelectionSort.SelectionSorter(list);
        }
        public void BinarySearchWorksCorrectly()
        {
            //Arrange
            int[] array = new int[] { -50, 3, 7, -125, 4, 0, -22, -178, 99, 120, -33, 9, 5, 2, 6, 1, 8, 10, 55, 110, 12, 34, 66 };
            Array.Sort(array);
            int numberToFind = 8;
            int position     = 13;

            var search = new BinarySearch();

            //Act
            int result = search.BinarySearchArray(array, numberToFind);

            //Assert
            Assert.AreEqual(position, result);
        }
Example #17
0
        public void TestFive()
        {
            // arrange
            var numbers = new int[] { 1, 3, 5, 7, 9 };
            // act
            var three = BinarySearch.FindNumber(numbers, 4);
            var one   = BinarySearch.FindNumber(numbers, 1);
            var nine  = BinarySearch.FindNumber(numbers, 9);
            var five  = BinarySearch.FindNumber(numbers, 5);

            // assert
            Assert.Equal(5, five);
            Assert.Equal(1, one);
            Assert.Equal(3, three);
            Assert.Equal(9, nine);
        }
Example #18
0
        public void BinarySearchWorks_Simple()
        {
            int[] elements = { 5, 8, 12 }; // { 6, 13, 14, 25, 33, 43, 51, 53, 64, 72, 84, 93, 95, 96, 97 };

            int result = BinarySearch.Find(elements, 12);

            Assert.Equal(result, 2);

            result = BinarySearch.Find(elements, 5);

            Assert.Equal(result, 0);

            result = BinarySearch.Find(elements, 8);

            Assert.Equal(result, 1);
        }
        public void Test_StepContinuous_6()
        {
            int[] array = new int[] { 0, 1, 2, 3, 4 };

            BinarySearch BS = new BinarySearch(array);

            BS.Step(2);
            Assert.AreEqual(0, BS.Left);
            Assert.AreEqual(4, BS.Right);
            Assert.AreEqual(1, BS.GetResult());

            BS.Step(2);
            Assert.AreEqual(0, BS.Left);
            Assert.AreEqual(4, BS.Right);
            Assert.AreEqual(1, BS.GetResult());
        }
        private static Battle FindElfsFirstWinByIncreasingTheirPower()
        {
            var stopwatch = Stopwatch.StartNew();

            var defaultConfig = PlayerConfiguration.DefaultConfig;

            var attackPowerWithOutLosses = BinarySearch.ForawrdSearch(defaultConfig.AttackPower,
                                                                      attackPower => attackPower * attackPower,
                                                                      attackPower =>
            {
                var battleResult = SimulateBattle(PlayerConfiguration.CreateConfig(attackPower));
                return(battleResult.elfResult.TotalElfDeaths == 0 ? -1 : 1);
            });

            return(SimulateBattle(PlayerConfiguration.CreateConfig(attackPowerWithOutLosses)).battle);
        }
Example #21
0
    /**
     * Reads in a sequence of integers from the whitelist file, specified as
     * a command-line argument; reads in integers from standard input;
     * prints to standard output those integers that do <em>not</em> appear in the file.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {

        // read the integers from a file
        In in = new In(args[0]);
        int[] whitelist = in.readAllInts();

        // sort the array
        Arrays.sort(whitelist);

        // read integer key from standard input; print if not in whitelist
        while (!StdIn.isEmpty()) {
            int key = StdIn.readInt();
            if (BinarySearch.indexOf(whitelist, key) == -1)
                StdOut.println(key);
        }
    }
        public void RankTest_KeyExist()
        {
            int[] data = { 1, 5, 10, 12, 37 };

            int index = BinarySearch.Rank(data, 1);

            Assert.AreEqual(0, index);
            index = BinarySearch.Rank(data, 5);
            Assert.AreEqual(1, index);
            index = BinarySearch.Rank(data, 10);
            Assert.AreEqual(2, index);
            index = BinarySearch.Rank(data, 12);
            Assert.AreEqual(3, index);
            index = BinarySearch.Rank(data, 37);
            Assert.AreEqual(4, index);
        }
        public void BinarySearchTest()
        {
            BinarySearch <int> binarySearch = new BinarySearch <int>();

            for (int i = 0; i < 100; i++)
            {
                FillRandom();
                Items.Sort();

                binarySearch.Items.Clear();
                binarySearch.Items.AddRange(this.Items);

                int standart = this.Items.BinarySearch(this.SearchItem) < -1 ? -1 : this.Items.BinarySearch(this.SearchItem);
                Assert.AreEqual(standart, binarySearch.ToFind(this.SearchItem));
            }
        }
        public void TryGetResultTest()
        {
            //Arrange

            List <int> list = new List <int>();

            for (int i = 0; i < 1000000; i++)
            {
                list.Add(i);
            }
            var binsearch = new BinarySearch <int>(list, list.Last());

            //Act
            binsearch.TryGetResult(list, list.Last());
            //Assert
        }
        static void BinarySearchExample03()
        {
            var array = new[]
            {
                Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()
            }.OrderBy(a => a).ToArray();

            var indexExpected = 0;

            Console.WriteLine($"Expected index: {indexExpected}");

            var index       = BinarySearch.IndexOf(array, array[indexExpected]);
            var indexString = index.HasValue ? index.Value.ToString() : "null";

            Console.WriteLine($"Actual index: {indexString}");
        }
        public void BinarySearch_SearchValueH_outH()
        {
            //arrange
            int expected = 9;

            //actual
            int[] massive = new int[10] {
                56, 2, 0, 8, (int)'H', 18, 7, 34, 11, 23
            };
            int          actual = -1;
            BinarySearch search = new BinarySearch(massive, (int)'H', out actual);

            //int actual = 0;
            //assert
            Assert.AreEqual <int>(expected, actual, "Ождалось {0}", parameters: actual);
        }
 static void Main(string[] args)
 {
     var sorter  = new InsertionSort();
     var numbers = new int[6] {
         8, 2, 4, 1, 3, 10
     };
     var numbers_unsorted = new int[6] {
         8, 2, 4, 1, 3, 10
     };
     // Do binary searching on sorted array
     var searching      = new BinarySearch();
     var found_at_index = searching.Search(10, sorter.sort(numbers));
     // Do linear searching on unsorted array
     var linear_searching      = new LinearSearch(numbers_unsorted);
     var found_at_index_linear = linear_searching.Searching(10);
 }
Example #28
0
        public static void Main(string[] args)
        {
            /*Union_Find a = new Union_Find();
             * a.FillInput();
             * a.Printinput();
             * a.SortByUnions();
             * a.PrintUnions();
             *
             * var a2 = new Union_Find_Algorithm();
             * a2.FillInput();
             * a2.PrintInput();
             * a2.PrintUnions();
             *
             * var a3 = new Quick_Union();
             * a3.FillInput();
             * a3.PrintInput();
             * a3.PrintUnions();
             *
             * var a4 = new Quick_Union_Improved();
             * a4.FillInput();
             * a4.PrintInput();
             * a4.PrintUnions();
             * Stopwatch stopwatch = Stopwatch.StartNew(); //creates and start the instance of Stopwatch
             *                                          //your sample code
             *
             * stopwatch.Stop();
             * Console.WriteLine(stopwatch.ElapsedMilliseconds);
             */

            int[] arr     = new int[] { 0, 1, 2, 3, 5, 6, 8, 9, 15, 17, 24, 27, 28, 29, 31, 37, 39, 40 };
            int   element = 38;
            int   number  = BinarySearch.Search(arr, element);

            if (number == -1)
            {
                Console.WriteLine($"Element {element} not found");
            }
            else
            {
                Console.WriteLine($"Element {element} is in position {number}");
            }

            int number2 = TwoStackDijkstraAlgorithm.CalculateExp("(1+((2+3)*(4*5)))");

            Console.WriteLine($"Element {number2}");
            CreateWebHostBuilder(args).Build().Run();
        }
Example #29
0
        public void Find()
        {
            var rand = new Random();

            for (int iii = 0; iii < 30; iii++)
            {
                var seed       = Enumerable.Range(1, 10);
                var randomSeed = seed.Where(x => rand.Next() % 2 == 0);

                var array = randomSeed.Concat(randomSeed).Concat(randomSeed).Concat(randomSeed)
                            .OrderBy(x => x)
                            .ToArray();

                for (int i = 1; i <= 10; i++)
                {
                    var firstIndex = Array.IndexOf(array, i);
                    var lastIndex  = Array.LastIndexOf(array, i);

                    var f = BinarySearch.FindFirst(array, i, x => x, Comparer <int> .Default);
                    var l = BinarySearch.LowerBound(array, 0, array.Length, i, x => x, Comparer <int> .Default);
                    var u = BinarySearch.UpperBound(array, 0, array.Length, i, x => x, Comparer <int> .Default);

                    // not found
                    if (firstIndex == -1)
                    {
                        f.Should().Be(-1);
                        l.Should().Be(-1);
                        u.Should().Be(-1);
                        continue;
                    }

                    array[f].Should().Be(i);
                    array[l].Should().Be(i);
                    array[u].Should().Be(i);

                    l.Should().Be(firstIndex);
                    u.Should().Be(lastIndex);
                }
            }

            // and empty
            var emptyArray = Enumerable.Empty <int>().ToArray();

            BinarySearch.FindFirst(emptyArray, 0, x => x, Comparer <int> .Default).Should().Be(-1);
            BinarySearch.LowerBound(emptyArray, 0, emptyArray.Length, 0, x => x, Comparer <int> .Default).Should().Be(-1);
            BinarySearch.UpperBound(emptyArray, 0, emptyArray.Length, 0, x => x, Comparer <int> .Default).Should().Be(-1);
        }
Example #30
0
        internal TElement InternalFindClosest(TKey key, bool selectLower, int comparerCount)
        {
            if (orderedData.Count == 0)
            {
                throw new ArgumentOutOfRangeException("Empty data is not supported.");
            }

            if (comparerCount == 1)
            {
                var index = BinarySearch.FindClosest(orderedData, 0, orderedData.Count, key, indexSelector, comparers[0], selectLower);
                return(orderedData[index]);
            }
            else
            {
                var lo = 0;
                var hi = orderedData.Count;

                for (int i = 0; i < comparerCount; i++)
                {
                    var comparer = comparers[i];

                    if (i == comparerCount - 1)
                    {
                        var index = BinarySearch.FindClosest(orderedData, lo, hi, key, indexSelector, comparer, selectLower);
                        return(orderedData[index]);
                    }
                    else
                    {
                        var newlo = BinarySearch.LowerBound(orderedData, lo, hi, key, indexSelector, comparer);
                        if (newlo == -1 || !(lo <= newlo) && (newlo < hi))
                        {
                            newlo = lo;
                        }
                        var newhi = BinarySearch.UpperBound(orderedData, lo, hi, key, indexSelector, comparer);
                        if (newhi == -1 || !(lo <= newhi) && (newhi < hi))
                        {
                            newhi = hi - 1;
                        }

                        lo = newlo;
                        hi = newhi + 1;
                    }
                }

                throw new InvalidProgramException();
            }
        }
Example #31
0
        public void BinarySerach_TypeNotImpelemntation_IComparer_ArgumentException()
        {
            Point[] points = { new Point()
                               {
                                   X = 10, Y = 10
                               }, new Point()
                               {
                                   X = 5, Y = 1
                               } };
            Point   elementToFind = new Point()
            {
                X = 5, Y = 1
            };

            Assert.Throws <ArgumentException>(
                () => BinarySearch.Search <Point>(points, elementToFind));
        }
Example #32
0
        public void BinarySearchRandomTest()
        {
            int number = 10;
            int index;
            int searchedElement;
            int searchedIndex;
            Random rand = new Random();

            // search in random collection
            int[] arr = GetRandom(number).ToArray();
            BinarySearch<int> search = new BinarySearch<int>(arr);
            Array.Sort(arr);

            searchedIndex = arr.Length - 1;
            searchedElement = arr.Last();
            index = search.Search(searchedElement);
            Assert.AreEqual(searchedIndex, index);

            searchedIndex = 0;
            searchedElement = arr.First();
            index = search.Search(searchedElement);
            Assert.AreEqual(searchedIndex, index);

            searchedIndex = number - 1 - rand.Next(number - 1);
            searchedElement = arr[searchedIndex];
            index = search.Search(searchedElement);
            Assert.AreEqual(searchedIndex, index);

            searchedElement = GetNotInArray(arr);
            index = search.Search(searchedElement);
            Assert.AreEqual(index, -1);
        }
Example #33
0
        public virtual void ShowHistogram(string qurl, string ourl, string dist)
        {
            Welcome.InnerHtml = "Nothing useful yet!";
            return;
            if (this.HistDist == null) {
                this.HistDist = new List<float> ();
                this.HistAcc = new List<float> ();
                this.HistBinSearch = new BinarySearch<float> ();
                int i = 0;
                float acc = 0;
                foreach (var line in File.ReadAllLines("Examples/imgsearch/hist.data")) {
                    var M = line.Split();
                    acc += float.Parse(M[1]);
                    if (i % 50 == 0) {
                        this.HistDist.Add(float.Parse(M[0]));
                        this.HistAcc.Add(acc);
                    }
                }
            }
            int pos;
            this.HistBinSearch.Search(float.Parse(dist), this.HistDist, out pos, 0, this.HistDist.Count);
            float pc = 100 * this.HistAcc[ pos ] / this.HistAcc[ this.HistAcc.Count - 1 ];
            Welcome.InnerHtml = string.Format (@"
                <table><tbody>
                    <tr><td style='border: 1pt solid gray; padding: 10pt; text-align: center;'>
                    <p>The image <br /><img src='{0}' /><br/> has a distance of {1} against<br /> <img src='{2}' /></p>
                </td><td style='border: 1pt solid gray; padding: 10pt; text-align: center;'>
                    <p>Their relative closeness, taking into account the whole
                    database, is in the percentile {3:0.00}%, meaning that the {4:0.00}% of
                the database is farther than it to the query.
                    </p><p>Graphically we can interpole the value from the following histogram of distances
                    <br />
                    <img width='300' height='300' src='histcophir.jpg' /></p>
                    The x axis is the distance. The y axis is for the average frequency computed using 200 random queries.

                        </td></tr></tbody></table>
                            ", qurl, dist, ourl, pc, 100 - pc);
        }
Example #34
0
        public static void Main(string[] args)
        {
            string cmd = null;
            string basename = null;
            string inputdir = null;
            string listfiles = null;
            string extension = null;
            string searchalg = "galloping";
            string interalg = "in-order-tree";
            OptionSet op = new OptionSet () {
                {"help", "Show help", (v) => cmd = "help"},
                {"build", "Build an index", (v) => cmd = "build"},
                {"dir=", "Directory to scan", (v) => inputdir = v},
                {"list=", "List of filenames (one per line)", (v) => listfiles = v},
                {"ext=", "Valid extension", (v) => extension = v},
                {"search", "Search for a query in an index", (v) => cmd = "search"},
                {"index=", "Base name for the index (build or search)", (v) => basename = v},
                {"search-algorithm=", "Choose the search algorithm (sequential|binary-search|galloping|backward-galloping)",
                    (v) => searchalg = v},
                {"intersection-algorithm=", "Choose an intersection algorithm (sequential|svs|small-adaptive|barbay-sequential|barbay-randomized|in-order-tree)",
                    (v) => interalg = v}
            };

            var Largs = op.Parse (args);
            if (Largs.Count > 0) {
                Console.WriteLine ("Unknown arguments, valid options:");
                op.WriteOptionDescriptions (Console.Out);
                return;
            }
            var seq = new SeqTextIR ();
            switch (cmd) {
            case "build":
                if (inputdir == null && listfiles == null) {
                    goto default;
                }
                if (basename == null) {
                    goto default;
                }
                // var seq_builder = SequenceBuilders.GetGolynskiSucc (12);
                //var seq_builder = SequenceBuilders.GetSeqXLB_SArray64 (12);
                var seq_builder = SequenceBuilders.GetSeqXLB_DiffSetRL64 (12, 31, new EliasDelta64 ());
                //var seq_builder = SequenceBuilders.GetSeqXLB_DiffSetRL2_64 (12, 31, new EliasDelta64 ());
                Console.WriteLine ("*** building SeqTextIR instance over {0} | filter {1}", inputdir, extension);
                //var seq_container = new List<int>();
                using (var seq_container = new SepDiskList32<int>(basename + ".memdata", 1<<12)) {
                    //var seq_container = new MemoryMappedList<int>("H", false); // false);
                    if (listfiles == null) {
                        seq.Build (GetFilenames (inputdir, extension), seq_builder, seq_container);
                    } else {
                        seq.Build (File.ReadAllLines (listfiles), seq_builder, seq_container);
                    }
                }
                Console.WriteLine ("*** saving");
                seq.Save (basename);
                /*{
                    string filename;
                    int sp;
                    int len;
                    Console.WriteLine ();
                    File.WriteAllText ("out-test-docid-0", seq.GetFileData (0, out filename, out sp, out len));
                    Console.WriteLine ("check file: {0}", filename);
                }*/
                break;
            case "search":
                if (basename == null) {
                    goto default;
                }
                ISearchAlgorithm<int> salg = null;
                switch (searchalg.ToLower ()) {
                case "galloping":
                    salg = new DoublingSearch<int> ();
                    break;
                //case "backward-galloping":
                //	salg = new BackwardDoublingSearch();
                //	break;
                case "binary-search":
                    salg = new BinarySearch<int> ();
                    break;
                case "sequential":
                    salg = new SequentialSearch<int> ();
                    break;
                default:
                    Console.WriteLine ("Unknown search algorithm: {0}", searchalg);
                    ShowHelp (op, cmd);
                    return;
                }
                IIntersection<int> ialg = null;
                switch (interalg.ToLower ()) {
                case "svs":
                    ialg = new SvS<int> (salg);
                    break;
                case "small-adaptive":
                    ialg = new SmallAdaptive<int> (salg);
                    break;
                case "barbay-sequential":
                    ialg = new BarbaySequential<int> (salg);
                    break;
                case "barbay-randomized":
                    ialg = new BarbayRandomized<int> (salg);
                    break;
                case "baeza-yates":
                    ialg = new BaezaYatesIntersection<int> (salg);
                    break;
                case "in-order-tree":
                    ialg = new InOrderUnbalancedTreeIntersection<int> (0.5, salg);
                    break;
                case "sequential":
                    throw new NotImplementedException ("sequential intersection is not supported. Instead use svs + sequential search");
                default:
                    ShowHelp (op, cmd);
                    return;
                }
                seq.Load (basename);
                while (true) {
                    Console.WriteLine ("query [enter]");
                    string query = Console.ReadLine ();
                    if (query == null || query == "") {
                        break;
                    }
                    Search (seq, query, ialg);
                }
                break;
            case "help":
            default:
                ShowHelp (op, cmd);
                break;
            }
        }
Example #35
0
        public void BinarySearchTest()
        {
            int number = 100;
            int index;
            int searchedElement;
            int searchedIndex;
            Random rand = new Random();

            int[] arr = Get(number).ToArray();
            BinarySearch<int> search = new BinarySearch<int>(arr);

            // search last element
            searchedIndex = arr.Length - 1;
            searchedElement = arr.Last();
            index = search.Search(searchedElement);
            Assert.AreEqual(searchedIndex, index);

            // search first element
            searchedIndex = 0;
            searchedElement = arr.First();
            index = search.Search(searchedElement);
            Assert.AreEqual(searchedIndex, index);

            // search random element
            searchedIndex = number - 1 - rand.Next(number - 1);
            searchedElement = arr[searchedIndex];
            index = search.Search(searchedElement);
            Assert.AreEqual(searchedIndex, index);
        }
 private int? ExecuteFind( int[] array, int value )
 {
     var searcher = new BinarySearch();
     return searcher.Find(array, value);
 }