搜索算法----线性搜索、二叉搜索

本文通过两个示例详细介绍了两种基本的搜索算法:线性搜索和二叉搜索。线性搜索适用于未排序的数据集,而二叉搜索则针对已排序的数组,通过不断缩小搜索范围提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 线性搜索
 */
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");
		}
	}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值