1 Star 0 Fork 0

CS-IMIS-23/20172306

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Searching.java 1.72 KB
一键复制 编辑 原始数据 按行查看 历史
package wek5;
public class Searching
{
/**
* Searches the specified array of objects using a linear search
* algorithm.
*
* @param data the array to be searched
* @param min the integer representation of the minimum value
* @param max the integer representation of the maximum value
* @param target the element being searched for
* @return true if the desired element is found
*/
public static <T>
boolean linearSearch(T[] data, int min, int max, T target)
{
int index = min;
boolean found = false;
while (!found && index <= max)
{
found = data[index].equals(target);
index++;
}
return found;
}
/**
* Searches the specified array of objects using a binary search
* algorithm.
*
* @param data the array to be searched
* @param min the integer representation of the minimum value
* @param max the integer representation of the maximum value
* @param target the element being searched for
* @return true if the desired element is found
*/
public static <T extends Comparable<T>>
boolean binarySearch(T[] data, int min, int max, T target)
{
boolean found = false;
int midpoint = (min + max) / 2; // determine the midpoint
if (data[midpoint].compareTo(target) == 0)
found = true;
else if (data[midpoint].compareTo(target) > 0)
{
if (min <= midpoint - 1)
found = binarySearch(data, min, midpoint - 1, target);
}
else if (midpoint + 1 <= max)
found = binarySearch(data, midpoint + 1, max, target);
return found;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/CS-IMIS-23/20172306.git
git@gitee.com:CS-IMIS-23/20172306.git
CS-IMIS-23
20172306
20172306
master

搜索帮助