首页 行业资讯 宠物日常 宠物养护 宠物健康 宠物故事

C#写的二分查找,有代码求指教

发布网友

我来回答

1个回答

热心网友

简单点评

严重点勿怪
种写
典型

1.
树立函数
概念



查找
肯定
让别
调用
函数


用户知道查找
数字位置

2.
检查参数
函数进
应该先检查参数
否合
叫防御式编程
数组


3.
函数体内
需要Console.WriteLine
语句
假设
类库函数
用户想
winform或者asp.net
调用
Console.WriteLine
何意义
候函数

值价值

4.
命名规范

随手写
请参考

查找(递归)
static
int
BinarySearch(int[]
array,
int
targetValue,
int
beginIndex,
int
endIndex)
{
if
(array
==
null)
{
throw
new
ArgumentNullException("...");
}
if
(beginIndex
<
0
||
endIndex
>
array.Length
-
1
||
beginIndex
>
endIndex)
{
throw
new
ArgumentException("...");
}
int
index
=
(beginIndex
+
endIndex)
/
2;
if
(targetValue
==
array[index])
{
return
index;
}
else
if
(targetValue
<
array[index])
{
return
BinarySearch(array,
targetValue,
beginIndex,
index
-
1);
}
else
{
return
BinarySearch(array,
targetValue,
index
+
1,
endIndex);
}
}

查找(非递归)
static
int
BinarySearch(int[]
array,
int
targetValue,
int
beginIndex,
int
endIndex)
{
if
(array
==
null)
{
throw
new
ArgumentNullException("...");
}
if
(beginIndex
<
0
||
endIndex
>
array.Length
-
1
||
beginIndex
>
endIndex)
{
throw
new
ArgumentException("...");
}
int
result
=
-1;
int
index
=
(beginIndex
+
endIndex)
/
2;
while
(beginIndex
<
endIndex)
{
if
(targetValue
==
array[index])
{
result
=
index;
break;
}
else
if
(targetValue
<
array[index])
{
endIndex
=
index
-
1;
}
else
{
beginIndex
=
index
+
1;
}
index
=
(beginIndex
+
endIndex)
/
2;
}
return
result;
}

热心网友

简单点评

严重点勿怪
种写
典型

1.
树立函数
概念



查找
肯定
让别
调用
函数


用户知道查找
数字位置

2.
检查参数
函数进
应该先检查参数
否合
叫防御式编程
数组


3.
函数体内
需要Console.WriteLine
语句
假设
类库函数
用户想
winform或者asp.net
调用
Console.WriteLine
何意义
候函数

值价值

4.
命名规范

随手写
请参考

查找(递归)
static
int
BinarySearch(int[]
array,
int
targetValue,
int
beginIndex,
int
endIndex)
{
if
(array
==
null)
{
throw
new
ArgumentNullException("...");
}
if
(beginIndex
<
0
||
endIndex
>
array.Length
-
1
||
beginIndex
>
endIndex)
{
throw
new
ArgumentException("...");
}
int
index
=
(beginIndex
+
endIndex)
/
2;
if
(targetValue
==
array[index])
{
return
index;
}
else
if
(targetValue
<
array[index])
{
return
BinarySearch(array,
targetValue,
beginIndex,
index
-
1);
}
else
{
return
BinarySearch(array,
targetValue,
index
+
1,
endIndex);
}
}

查找(非递归)
static
int
BinarySearch(int[]
array,
int
targetValue,
int
beginIndex,
int
endIndex)
{
if
(array
==
null)
{
throw
new
ArgumentNullException("...");
}
if
(beginIndex
<
0
||
endIndex
>
array.Length
-
1
||
beginIndex
>
endIndex)
{
throw
new
ArgumentException("...");
}
int
result
=
-1;
int
index
=
(beginIndex
+
endIndex)
/
2;
while
(beginIndex
<
endIndex)
{
if
(targetValue
==
array[index])
{
result
=
index;
break;
}
else
if
(targetValue
<
array[index])
{
endIndex
=
index
-
1;
}
else
{
beginIndex
=
index
+
1;
}
index
=
(beginIndex
+
endIndex)
/
2;
}
return
result;
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com