java实现顺序查找并输出查找的次序

来源:互联网 发布:网络语言有 编辑:程序博客网 时间:2024/05/22 10:57

java中的顺序查找是一种简单的查找方式,实现过程中注意方法的调用及参数的使用;

java代码实现:

import java.util.Scanner;


public class Search {
//创建数组
public static int[] Data = {1,7,9,12,15,
16,20,32,35,
67,78,80,83,
89,90,92,97,
108,120,177};

static int Counter = 1;  //查找次数计数器

public static void main(String[] args) {
System.out.print("请输入你要查找的数值:");
//读入输入数据
Scanner sc = new Scanner(System.in);
int keyvalue = sc.nextInt();
//调用顺序查找的方法
if(Seq_Search((int)keyvalue)){
//换行
System.out.println("");
//输出总共查找的次数
System.out.println("Search Time ="+(int)Counter);
}else{
//换行
System.out.println("");
//未找到数据
System.out.println("没有找到你所要找的数据!");
}
}
public static boolean Seq_Search(int key){
for(int i = 0;i<20;i++){
//输出数据
System.out.print("["+(int)Data[i]+"]");
//查找数据
if((int)key == (int)Data[i]){
return true;//返回true
}
Counter++;//计时器递增
}
return false;
}
}

0 0