2 Star 0 Fork 0

CS-IMIS-23/20172309_javaProgramming

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Searching.java 2.05 KB
一键复制 编辑 原始数据 按行查看 历史
20172309 提交于 7年前 . eg10.11 PhoneList2
//********************************************************************
// Searching.java Author: Lewis/Loftus
//
// Demonstrates the linear search and binary search algorithms.
//********************************************************************
public class Searching
{
//-----------------------------------------------------------------
// Searches the specified array of 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].equals(target))
found = true;
else
index++;
}
if (found)
return list[index];
else
return null;
}
//-----------------------------------------------------------------
// Searches the specified array of objects for the target using
// a binary search. Assumes the array is already sorted in
// ascending order when it is passed in. Returns a reference to
// the target object from the array if found, and null otherwise.
//-----------------------------------------------------------------
public static Comparable binarySearch(Comparable[] list,
Comparable target)
{
int min=0, max=list.length, mid=0;
boolean found = false;
while (!found && min <= max)
{
mid = (min+max) / 2;
if (list[mid].equals(target))
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/20172309_javaProgramming.git
git@gitee.com:CS-IMIS-23/20172309_javaProgramming.git
CS-IMIS-23
20172309_javaProgramming
20172309_javaProgramming
master

搜索帮助