发布网友
共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;
}