顺序查找算法
import java.util.ArrayList;
import java.util.List;
public class Serarch {
public static void main(String[] args) {
int size = (int) (Math.random()*31);
int[] a = new int[size];
jitu.randomList(a,size);
// 查找1
int search_num = (int) (Math.random()*100);
System.out.println("待查找数据:"+search_num);
System.out.println("查找目标数组:");
for (int j : a){
System.out.print(j+"\t");
}
System.out.println();
List<Integer> result = orderSearch(search_num,a);
if (result.size() <= 1){
if (result.get(0) == -1){
System.out.println("没有找到元素");
}else{
System.out.println("下标:"+result.get(0));
}
}else {
for (int i : result){
System.out.print(i+"\t");
}
}
}
public static List<Integer> orderSearch(int search_num, int[] a) {
ArrayList<Integer> index = new ArrayList<Integer>();
for (int i=0;i<a.length;i++){
if (search_num == a[i]){
index.add(i);
}
}
if (index.size() > 0){
return index;
}
else {
index.add(-1);
return index;
}
}
}
查找流程
对输入的数据,使用循环依次比对数组中是否存在该数据。以上,如果查找到该数据,则返回该元素的数组下标
折半查找算法
public static int zheBan_search(int search_num,int len,int[] a){
int mid,low,high;
low = 0;
high = len -1;
while (low<=high){
mid = (high + low)/2;
if (a[mid] == search_num){
return mid;
}else if (a[mid] > search_num){
high = mid-1;
}else {
low = mid + 1;
}
}
return -1;
}
运行结果:
数组长度:30
待查找数据:50
查找目标数组:
65 76 92 21 16 27 89 54 98 50 44 68 56 94 9 43 96 65 13 52 76 30 37 24 84 40 32 43 5 73
将数组进行排序
5 9 13 16 21 24 27 30 32 37 40 43 43 44 50 52 54 56 65 65 68 73 76 76 84 89 92 94 96 98
开始折半查找
目标所在位置为:14
查找流程
首先数组排序,再按照以下流程进行查找