1 Star 1 Fork 0

CS-IMIS-23/20172313yukunpeng

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Searching.java 1.63 KB
一键复制 编辑 原始数据 按行查看 历史
package srcNo8;
//**************************************************************************************
// Searching.java Author:Yu Kunpeng
//
// Demonstrates the linear search and binary search algorithms
//**************************************************************************************
public class Searching {
//-----------------------------------------------------------------------------------
// Searches the specified array objects for the target using
// a linear search. Returns a reference to the target object from
// the array if found ,and null otherwise
//-----------------------------------------------------------------------------------
public static Comparable linearSearch(Comparable[] list, Comparable target) {
int index = 0;
boolean found = false;
while (!found && index < list.length) {
if (list[index].compareTo(target) == 0)
found = false;
else
index++;
}
if (found)
return list[index];
else
return null;
}
public static Comparable binarySearch(Comparable[] list, Comparable target) {
int min = 0, max = list.length - 1, mid = 0;
boolean found = false;
while (!found && min <= max) {
mid = (min + max) / 2;
if (list[mid].compareTo(target) == 0)
found = true;
else if (target.compareTo(list[mid]) < 0)
max = mid - 1;
else
min = mid + 1;
}
if (found)
return list[mid];
else
return null;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/CS-IMIS-23/20172313yukunpeng.git
git@gitee.com:CS-IMIS-23/20172313yukunpeng.git
CS-IMIS-23
20172313yukunpeng
20172313yukunpeng
master

搜索帮助