本程序使用线性搜索算法从n个数中查找一个数。
/* Program: 线性搜索示例
* @author: 理工云课堂
* Input: 元素个数,每个元素值,待查找数据的值
* Output:待查找数的位置*/
import java.util.Scanner;
class LinearSearchExample
{
public static void main(String args[])
{
int counter, num, item, array[];
//捕获用户输入
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
//创建一个数组来存放所有整数
array = new int[num];
System.out.println("Enter " + num + " integers");
//循环将用户输入的数存放到数组中
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt(); System.out.println("Enter the search value:");
item = input.nextInt(); for (counter = 0; counter < num; counter++)
{
if (array[counter] == item)
{
System.out.println(item+" is present at location "+(counter+1));
/*找到了这个数就停止查找,使用break终止for循环。*/
break;
}
}
if (counter == num)
System.out.println(item + " doesn't exist in array.");
}
}
输出1:
Enter number of elements:
6
Enter 6 integers
22
33
45
1
3
99
Enter the search value:
45
45 is present at location 3
输出2:
Enter number of elements: Enter integers Enter the search value: doesn't exist in array.