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?
Array.Sortinstead of writing your own bubble sort implementation.lis never >=r. So you never enter thewhileloop. I think you wantwhile(l<=r)elsein thewhileloop will never be reached sincearr[m]can only be equal to, less than, or greater thant. There are no other possibilities.min the loop.