Phoenix.1993
Phoenix.1993

Reputation: 85

Binary search of a sorted array error

using System.IO;
using System;
class Class1
{
    static void Main(string[] args)
    {
        int[] arr = new int[10] { 1,3,2,4,5,7,6,8,10,9};
        int l = 1, r = 10, m = 0,t;

        sort(arr, 10); 
        int i;
        for (i = 0; i < 10; i++)
        {
            Console.Write(arr[i] + "\t");
        }
        Console.WriteLine("Please entert the number");
        t = Convert.ToInt32(Console.ReadLine());

        m = (l + r) / 2;

        while(l>=r)
        {
            if (arr[m] == t)
               Console.WriteLine("value is : " + m);
            if (arr[m] < t)
                l = m + 1;
            if (arr[m] > t)
                r = m - 1;
            else
                Console.WriteLine("Target was found at index  " + arr[m]);
        }
    }

    static void sort(int[] dataset, int n)
    {
        int i, j;
        for (i = 0; i < n; i++)
            for (j = n - 1; j > i; j--)
                if (dataset[j] < dataset[j - 1])
                {
                    int temp = dataset[j];
                    dataset[j] = dataset[j - 1];
                    dataset[j - 1] = temp;
                }
    }
}

I tried running this program. I got output as :

sh-4.3$ mcs *.cs -out:main.exe
sh-4.3$ mono main.exe
1 2 3 4 5 6 7 8 9
10
Please enter the number
5
sh-4.3$

What should I do to get the output of binary search from the sorted array?

Upvotes: 0

Views: 113

Answers (1)

Vikhram
Vikhram

Reputation: 4394

There are lots of issues with your code

  1. Bad formatting - make it difficult to read
  2. Bad variable names - make it difficult to understand
  3. Variables not declared close to where they are being used
  4. Not using inbuilt routine for sort (assuming your focus is on learning binary search)

Now, logically the code fails, since the while loop for your binary search is flawed. Below is the correct code for your main - I have tried to keep it as similar to your code as possible, so you can understand the issues

static void Main(string[] args) {
    int[] arr = new int[10] { 1, 3, 2, 4, 5, 7, 6, 8, 10, 9 };


    sort(arr, 10);
    int i;
    for (i = 0; i < 10; i++) {
        Console.Write(arr[i] + "\t");
    }

    int t;
    Console.WriteLine("Please entert the number");
    t = Convert.ToInt32(Console.ReadLine());

    bool found = false;
    int l = 0, r = arr.Length - 1, m = 0;
    while (!found && l <= r) {
        m = (l + r) / 2;
        if (arr[m] == t)
            found = true;
        else if (arr[m] < t)
            l = m + 1;
        else if (arr[m] > t)
            r = m - 1;
    }
    if (found)
        Console.WriteLine($"value {t} is located at index {m}");
    else
        Console.WriteLine($"value {t} not found");
}

Upvotes: 1

Related Questions