Generics C#

Binary Search a Sorted List

This C# program demonstrates how to binary search a sorted list of elements.

Program.cs

using System;
using System.Collections.Generic;


namespace XoaX {

    class Program {
        static void Main(string[] args) {
            List<string> qPentateuch = new List<string>();

            qPentateuch.Add("Genesis");
            qPentateuch.Add("Exodus");
            qPentateuch.Add("Leviticus");
            qPentateuch.Add("Numbers");
            qPentateuch.Add("Deuteronomy");

            // Sort the list. So that we can search it
            qPentateuch.Sort();

            Console.WriteLine("Pentateuch:");
            Console.WriteLine("-----------");
            foreach (string sBook in qPentateuch) {
                Console.WriteLine(sBook);
            }
            Console.WriteLine("");

            // Perform three searches: Joshua is not in the list.
            string sSearch = "Genesis";
            int iIndex = qPentateuch.BinarySearch(sSearch);
            Console.WriteLine(sSearch + " returned " + iIndex + " from the binary search.");
            sSearch = "Joshua";
            iIndex = qPentateuch.BinarySearch(sSearch);
            Console.WriteLine(sSearch + " returned " + iIndex + " from the binary search.");
            sSearch = "Deuteronomy";
            iIndex = qPentateuch.BinarySearch(sSearch);
            Console.WriteLine(sSearch + " returned " + iIndex + " from the binary search.");
        }
    }

}
 

Output

Pentateuch:
-----------
Deuteronomy
Exodus
Genesis
Leviticus
Numbers

Genesis returned 2 from the binary search.
Joshua returned -4 from the binary search.
Deuteronomy returned 0 from the binary search.
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.