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;
}
}
}
我试过运行这个程序。我输出为:
sh-4.3 $ mcs * .cs -out:main.exe
sh-4.3 $ mono main.exe
1 2 3 4 5 6 7 8 9
10个
请输入数字
5
SH-4.3 $
如何从排序数组中获取二进制搜索的输出?
答案 0 :(得分:2)
您的代码存在很多问题
现在,逻辑上代码失败了,因为二进制搜索的while循环存在缺陷。下面是您主要的正确代码 - 我试图尽可能保持与您的代码类似,以便您可以理解问题
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");
}