Sorting, Searching And Some Other Useful Programs

Introduction

Here are some useful programs implemented using C#. Of course, most of you might have programmed them using different other programming languages. Hence I am not going to explain to you what each program does. I am going to show how to implement them using C#. The following is the list of programs for your reference.

Linear Search Program in C#

Linear search is one of the simplest searching algorithms used to find a specific element in a list or array. In this article, we will walk you through how to implement a linear search algorithm in C#. Linear search, also known as sequential search, is a straightforward searching algorithm that checks each element in a list or array one by one until a match is found. It is the most basic searching technique and is suitable for small datasets. However, for larger datasets, more efficient algorithms like binary search are preferred.

Here, the code below implements Linear search.

using System;
class LinearSearch
{
    public static void Main()
    {
        Console.WriteLine("Enter the number of elements you want to hold in the array?");
        if (!int.TryParse(Console.ReadLine(), out int length) || length <= 0)
        {
            Console.WriteLine("Invalid input. Please enter a positive integer for the array size.");
            return;
        }
        int[] array = new int[length];
        Console.WriteLine("\nEnter array elements:\n");
        for (int i = 0; i < length; i++)
        {
            Console.Write($"Enter element {i + 1}: ");
            if (!int.TryParse(Console.ReadLine(), out array[i]))
            {
                Console.WriteLine("Invalid input. Please enter a valid integer.");
                i--; // Retry input for the same element
            }
        }
        Console.WriteLine("Enter the search element:\n");
        if (!int.TryParse(Console.ReadLine(), out int searchValue))
        {
            Console.WriteLine("Invalid input. Please enter a valid integer to search for.");
            return;
        }
        for (int i = 0; i < length; i++)
        {
            if (array[i] == searchValue)
            {
                Console.WriteLine("-------------------------");
                Console.WriteLine("Search successful");
                Console.WriteLine($"Element {searchValue} found at location {i + 1}\n");
                return;
            }
        }

        Console.WriteLine("Search unsuccessful");
    }
}

Output

linear search program

Binary Search Program in C#

Binary search is a highly efficient searching algorithm used to find a specific element in a sorted list or array. In this article, we will guide you through implementing a binary search algorithm in C#.Binary search is a divide-and-conquer algorithm that repeatedly divides a sorted list or array into two halves and compares the middle element with the target element. Based on the comparison, it narrows down the search range, effectively reducing the search space by half with each iteration. This makes binary search significantly faster than linear search, especially for large datasets.

Here, the code below implements Binary search.

using System;
class BinarySearch
{
    public static void Main()
    {
        // Initialize an array to store elements
        int[] array = new int[100];
        Console.WriteLine("Enter the number of elements in the array:");
        string input = Console.ReadLine();
        int length = Int32.Parse(input);
        Console.WriteLine("-----------------------");
        Console.WriteLine("Enter array elements:");
        Console.WriteLine("-----------------------");
        // Input array elements
        for (int i = 0; i < length; i++)
        {
            string elementInput = Console.ReadLine();
            array[i] = Int32.Parse(elementInput);
        }
        Console.WriteLine("--------------------");
        Console.WriteLine("Enter the search element:");
        Console.WriteLine("--------------------");
        // Input the value to search for
        string searchInput = Console.ReadLine();
        int searchValue = Int32.Parse(searchInput);
        int low = 0;
        int high = length - 1;
        // Perform binary search
        while (low <= high)
        {
            int mid = (low + high) / 2;
            if (searchValue < array[mid])
                high = mid - 1;
            else if (searchValue > array[mid])
                low = mid + 1;
            else if (searchValue == array[mid])
            {
                Console.WriteLine("-----------------");
                Console.WriteLine("Search successful");
                Console.WriteLine("-----------------");
                Console.WriteLine("Element {0} found at location {1}\n", searchValue, mid + 1);
                return;
            }
        }
        // If the element is not found
        Console.WriteLine("Search unsuccessful");
    }
}

Output

binary search

Selection Sort Program in C#

Selection sort is a simple and straightforward sorting algorithm used to sort a list or array of elements. In this article, we'll guide you through implementing a selection sort algorithm in C#. Selection sort is a comparison-based sorting algorithm that divides the input list into two parts: the sorted part and the unsorted part. It repeatedly selects the minimum (or maximum, depending on the sorting order) element from the unsorted part and moves it to the end of the sorted part. This process continues until the entire list is sorted.

Here, the code below implements the Selection sort.

using System;
class SelectionSort
{
    public static void Main()
    {
        // Initialize an array to store elements
        int[] array = new int[100];
        int min, pass, i;
        Console.WriteLine("Enter the number of elements in the array:");
        string input = Console.ReadLine();
        int length = Int32.Parse(input);
        Console.WriteLine("-----------------------");
        Console.WriteLine("Enter array elements:");
        Console.WriteLine("-----------------------");
        // Input array elements
        for (int j = 0; j < length; j++)
        {
            string elementInput = Console.ReadLine();
            array[j] = Int32.Parse(elementInput);
        }
        // Perform selection sort
        for (pass = 0; pass < length - 1; pass++)
        {
            min = pass;

            for (i = pass + 1; i < length; i++)
            {
                if (array[min] > array[i])
                    min = i;
            }

            // Swap elements if needed
            if (min != pass)
            {
                int temp = array[pass];
                array[pass] = array[min];
                array[min] = temp;
            }
        }
        Console.WriteLine("--------------------------------------------");
        Console.WriteLine("Sorted elements of an array (selection sort):");
        // Print sorted elements
        for (int j = 0; j < length; j++)
        {
            Console.WriteLine(array[j]);
        }
    }
}

Output

selection sort

Bubble Sort Program in C#

Bubble sort is a simple sorting algorithm used to sort a list or array of elements by repeatedly swapping adjacent elements if they are in the wrong order. In this article, we will guide you through implementing a bubble sort algorithm in C#. Bubble sort is a comparison-based sorting algorithm that works by repeatedly stepping through the list, comparing each pair of adjacent items, and swapping them if they are in the wrong order. This process is repeated until no more swaps are needed, indicating that the list is sorted.

Here, the code below implements Bubble Sort.

using System;
class BubbleSort
{
    public static void Main()
    {
        // Initialize an array to store elements
        int[] array = new int[100];
        Console.WriteLine("Enter the number of elements in the array:");
        string input = Console.ReadLine();
        int length = Int32.Parse(input);
        Console.WriteLine("-----------------------");
        Console.WriteLine("Enter array elements:");
        Console.WriteLine("-----------------------");
        // Input array elements
        for (int j = 0; j < length; j++)
        {
            string elementInput = Console.ReadLine();
            array[j] = Int32.Parse(elementInput);
        }
        int limit = length - 1;
        // Perform bubble sort
        for (int pass = 0; pass < length - 1; pass++)
        {
            for (int j = 0; j < limit - pass; j++)
            {
                if (array[j] > array[j + 1])
                {
                    // Swap elements if needed
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
        Console.WriteLine("------------------------------------------------");
        Console.WriteLine("Sorted elements of an array (bubble sort):");
        // Print sorted elements
        for (int j = 0; j < length; j++)
        {
            Console.WriteLine(array[j]);
        }
    }
}

Output

bubble sort

Finding the Largest and Smallest Number 

Here, the code below finds the largest and smallest number.

using System;
class Test
{
    public static void Main()
    {
        int n;
        float large, small;
        int[] a = new int[50];
        Console.WriteLine("Enter the size of Array");
        string s = Console.ReadLine();
        n = Int32.Parse(s);
        Console.WriteLine("Enter the array elements");
        for (int i = 0; i < n; i++)
        {
            string s1 = Console.ReadLine();
            a[i] = Int32.Parse(s1);
        }
        Console.Write("");
        large = a[0];
        small = a[0];
        for (int i = 1; i < n; i++)
        {
            if (a[i] > large)
                large = a[i];
            else if (a[i] < small)
                small = a[i];
        }
        Console.WriteLine("Largest element in the array is {0}", large);
        Console.WriteLine("Smallest element in the array is {0}", small);
    }
}

Output

smallest /largest

Fibonacci Series in C#

The Fibonacci series is a famous mathematical sequence that starts with 0 and 1, and each subsequent number in the sequence is the sum of the two preceding ones. In this article, we will explore how to generate the Fibonacci series in C#.

Here, the code below implements the Fibonacci Series.

using System;
class FS
{
    public static void Main()
    {
        int n;
        Console.WriteLine("Number of terms to be generated?");
        string s = Console.ReadLine();
        n = Int32.Parse(s);
        Console.WriteLine("*******************************");
        Console.WriteLine("Fibonacci sequence up to {0}", n);
        Console.WriteLine("*******************************");
        GenerateFib.Generate(n);
    }
}
class GenerateFib
{
    private static int f1 = 0;
    private static int f2 = 1;
    public static void Generate(int n)
    {
        int temp;

        if (n < 2)
        {
            f1 = 0;
            f2 = 1;
        }
        else
        {
            Generate(n - 1);
            temp = f2;
            f2 = f1 + f2;
            f1 = temp;
        }
        Console.WriteLine(f1);
    }
}

Output

Fibonacci sequence

Palindrome Program in C#

A palindrome is a word, phrase, or sequence of characters that reads the same forwards and backward (ignoring spaces, punctuation, and capitalization). In this article, we'll explore how to create a C# program to check if a given input is a palindrome. A palindrome is a sequence of characters that remains the same when its characters are reversed. Examples of palindromes include "racecar," "level," "madam," and "A man, a plan, a canal, Panama!".

Here, the code below implements Palindrome.

using System;
class Palindrome
{
    public static void Main()
    {
        int n, num, digit, sum = 0, rev = 0;
        string s;
        Console.WriteLine("*******************");
        Console.WriteLine("Please enter a number");
        Console.WriteLine("*******************");
        s = Console.ReadLine();
        num = Int32.Parse(s);
        n = num;
        do
        {
            digit = num % 10;
            sum += digit;
            rev = rev * 10 + digit;
            num /= 10;
        } while (num != 0);
        Console.WriteLine("*******************************");
        Console.WriteLine("Sum of the digits of the number = {0}", sum);
        Console.WriteLine("************************");
        Console.WriteLine("Reverse of the number = {0}", rev);
        Console.WriteLine("************************");
        if (n == rev)
            Console.WriteLine("The number is a palindrome");
        else
            Console.WriteLine("The number is not a palindrome");
    }
}

Output

palindrome program

Generating Pascal Triangle in C#

Pascal's Triangle is a fascinating mathematical structure named after the French mathematician Blaise Pascal. It is a triangular array of numbers in which each number is the sum of the two numbers directly above it. In this article, we'll explore how to generate Pascal's Triangle using C#. Pascal's Triangle starts with a single number, 1, at the top. Each subsequent row is constructed by adding the two numbers diagonally above it. The triangle is an infinite structure, but typically only a few rows are calculated.

Here, the code below implements Generating Pascal Triangle.

using System;
class PascalTriangle
{
    public static void Main()
    {
        int binom = 1, q = 0, r, x;
        Console.WriteLine("Enter the number of rows");
        string s = Console.ReadLine();
        int p = Int32.Parse(s);
        Console.WriteLine(p);
        Console.WriteLine("The Pascal Triangle");
        while (q < p)
        {
            for (r = 40 - (3 * q); r > 0; --r)
                Console.Write(" ");
            for (x = 0; x <= q; ++x)
            {
                if ((x == 0) || (q == 0))
                    binom = 1;
                else
                    binom = (binom * (q - x + 1)) / x;

                Console.Write(binom);
            }
            Console.Write("\n ");
            ++q;
        }
    }
}

Output

pascal traingle


Similar Articles