java-线性查找法

方法一:

package m;

import java.util.*;

public class find {

public static int[]data={2,4,6,8,0,1,22,56,7,89,54};

public static void  main(String[]args)

{

System.out.println("please enter the data you will find:");

Scanner scan=new Scanner(System.in);

int key=scan.nextInt();

if(lineFind(key))

{

System.out.println("find success");

}

else

System.out.println("find failed");

}

public static boolean lineFind(int key)

{

for(int i=0;i<data.length-1;i++)

{

if(key==data[i])

{

System.out.println("the data is:"+data[i]+" and is  in array "+(i+1));

return true;

}

}

return false;

}

}


方法二:将要查找的数字放在数组最后一位的改进算法

package m;

import java.util.*;

public class find {

public static int max=10;

public static int[]data=new int[max+1];

public static void  main(String[]args)

{

int[]data1={1,2,4,6,7,9,0,11,33,55};

for(int i=0;i<data1.length;i++)

data[i]=data1[i];

System.out.println("please enter the data you will find:");

Scanner scan=new Scanner(System.in);

int key=scan.nextInt();

data[max]=key;

if(lineFind2(key))

{

System.out.println("success");

}

else

{

System.out.println("failed");

}

}

public static boolean lineFind2(int key)

{

int index=0;

for(int i=0;i<=data.length;i++)

{

if(key==data[i])

{

if(i==max)

{

System.out.println("");

}

else

System.out.println("the data "+data[i]+" is in array "+(i+1));

return true;

}//if

}//for

return false;

}


}


本文出自 “hagar” 博客,谢绝转载!

java-线性查找法,布布扣,bubuko.com

java-线性查找法

上一篇:java-折半查找法


下一篇:HTTP协议