常见查找算法-JAVA实现

博客介绍了两种查找算法。线性查找适用于顺序或链接存储的线性表,时间复杂度为O(n);二分查找适用于已经有序的情况,时间复杂度为O(log2n)。

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

package org.nxt.algorithm.search;
/**
 * the bean of comparable
 * @author nanxiaotao
 *
 */
public class ComparableBean implements Comparable<ComparableBean> {

	private int value;
	

	public int getValue() {
		return value;
	}



	public void setValue(int value) {
		this.value = value;
	}



	@Override
	public int compareTo(ComparableBean o) {
		if(this.value<o.getValue()) {
			return -1;
		}else if(this.value==o.getValue()) {
			return 0;
		}else {
			return 1;
		}
	}

}

1.线性查找

   适用场景:顺序存储或链接存储的线性表

   时间复杂度:O(n)

package org.nxt.algorithm.search;


/**
 * linear search
 * @author nanxiaotao
 *
 */
public class LinearSearch {
	
	/**
	 * search
	 * @param datas aggregate of the data
	 * @param target the object to look for
	 * @return
	 */
	public static ComparableBean search(ComparableBean [] datas,ComparableBean target) {
		
		ComparableBean result=null;//Object found
		
		for(int i=0;i<datas.length;i++) {
			//Traverse the collection
			ComparableBean item=datas[i];//get the element of a collection by index
			//compare the current element to the target object
			if(0==item.compareTo(target)) {
				//if they are equal,assign and break out of the loop
				result=item;
				break;
			}
		}
		
		return result;
		
	}

}

1.二分查找

   适用场景:已经有序

   时间复杂度:O(log2n)

package org.nxt.algorithm.search;
/**
 * Binary Search
 * @author nanxiaotao
 *
 */
public class BinarySearch {
	
	/**
	 * search
	 * @param datas datas aggregate of the data
	 * @param target target the object to look for
	 */
	public static ComparableBean search(ComparableBean [] datas,ComparableBean target) {
		
		ComparableBean result=null;//Object found
		
		int first=0;//the first index of collection
		
		int last=datas.length-1;//the last index of collection
		
		int mid;//the middle index of colleciton
		
		/**
		 * Traverse the collection
		 * suspensive condition:
		 *                     1:find the target
		 *                     2:the first index equals the last index
		 */
		while(result==null&&first<=last) {
			mid=(first+last)/2;//compute the middle index
			if(datas[mid].compareTo(target)==0) {
				//equal
				result=datas[mid];
			}else {
				if(datas[mid].compareTo(target)==-1) {
					//smaller
					first=first+1;
				}else {
					//bigger
					last=last-1;
				}
			}
			
		}
		
		return result;
		
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值