/**
* 线性搜索
*/
package com.szy.structure.search;
import java.util.Scanner;
public class SequentialSearch
{
public static void main(String[] args)
{
int number[]={10,-2,30,22,1,2,5,4,3,20};
Scanner scanner=new Scanner(System.in);
System.out.println("Input the number you want to search:");
int input=scanner.nextInt(); //不考虑输入的内容是否合法
//线性查找
for (int i = 0; i < number.length; i++)
{
if(number[i]==input)
{
System.out.println(input+" was found at the position of "+(i+1));
break;
}
}
System.out.println("The number you input wasn't in the array");
}
}
/**
* 二叉搜索
*/
package com.szy.structure.search;
import java.util.Scanner;
public class BinarySearch
{
public static void main(String[] args)
{
//假设数组已经排好序,没排序好的使用排序算法排序
int number[]={1,2,4,6,8,32,44,67,89,100,110};
Scanner scanner=new Scanner(System.in);
System.out.println("Input the number you want to search:");
int input=scanner.nextInt(); //不考虑输入的内容是否合法
int lowbound=0;
int upperbound=number.length-1;
int mid=(lowbound+upperbound)/2;
while((input!=number[mid]&&(lowbound<=upperbound)))
{
if (input>number[mid])
{
lowbound=mid+1;
}
else
{
upperbound=mid-1;
}
mid=(lowbound+upperbound)/2;
}
if (input==number[mid])
{
System.out.println(input+" was found at the position of "+(mid+1));
}
else
{
System.out.println("The number you input wasn't in the array");
}
}
}