java简单查找回顾

本文介绍并实现了两种常见的查找算法:二分查找和哈希查找。通过Java代码示例详细展示了这两种算法的工作原理及具体应用。对于有序数组,二分查找能够高效定位元素;而哈希查找则适用于任何类型的数据,通过哈希函数快速确定元素位置。

package jvm;

public class Dichotomy {

	public static void main(String[] args) {
		int[] is = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
		System.out.println("循环:" + binarySearch(is, 4));
		System.out.println("迭代:" + binarySearch(is, 4, 0, is.length - 1));
	}

	/**
	 * 二分法:顺序、循环
	 * 
	 * @param data
	 * @param i
	 * @return
	 */
	private static int binarySearch(int[] data, int i) {
		if (data == null || data.length <= 0) {
			return -1;
		}
		int low = 0;
		int high = data.length - 1;
		while (low <= high) {
			int mid = (low + high) / 2;
			if (data[mid] == i) {
				return mid;
			} else if (data[mid] < i) {
				low = mid + 1;
			} else if (data[mid] > i) {
				high = mid - 1;
			}
		}
		return -1;
	}

	private static int binarySearch(int[] data, int i, int low, int high) {
		if (data == null || data.length <= 0) {
			return -1;
		}
		if (low <= high) {
			int mid = (low + high) / 2;
			if (data[mid] == i) {
				return i;
			} else if (data[mid] < i) {
				binarySearch(data, i, mid + 1, high);
			} else if (data[mid] > i) {
				binarySearch(data, i, low, mid - 1);
			}

		}
		return i;
	}

}

查找算法之哈希查找

点击打开链接

package jvm;
public class HashSearch {

	public static void main(String[] args) {
		//“除法取余法”
        int hashLength = 13;

        int [] array  = { 13, 29, 27, 28, 26, 30, 38 };

        //哈希表长度
        int[] hash = new int[hashLength];
        //创建hash
        for (int i = 0; i < array.length; i++)
        {
            insertHash(hash, hashLength, array[i]);
        }
        
        int result = searchHash(hash,hashLength, 29);

		if (result != -1)
			System.out.println("已经在数组中找到,索引位置为:" + result);
		else
			System.out.println("没有此原始");
	}

	/****
	 * Hash表检索数据
	 * 
	 * @param hash
	 * @param hashLength
	 * @param key
	 * @return
	 */
	public static int searchHash(int[] hash, int hashLength, int key) {
		// 哈希函数
		int hashAddress = key % hashLength;

		// 指定hashAdrress对应值存在但不是关键值,则用开放寻址法解决
		while (hash[hashAddress] != 0 && hash[hashAddress] != key) {
			hashAddress = (++hashAddress) % hashLength;
		}

		// 查找到了开放单元,表示查找失败
		if (hash[hashAddress] == 0)
			return -1;
		return hashAddress;

	}

	/***
	 * 数据插入Hash表
	 * 
	 * @param hash 哈希表
	 * @param hashLength
	 * @param data
	 */
	public static void insertHash(int[] hash, int hashLength, int data) {
		// 哈希函数
		int hashAddress = data % hashLength;

		// 如果key存在,则说明已经被别人占用,此时必须解决冲突
		while (hash[hashAddress] != 0) {
			// 用开放寻址法找到
			hashAddress = (++hashAddress) % hashLength;
		}

		// 将data存入字典中
		hash[hashAddress] = data;
	}
}

//运行结果:
//已经在数组中找到,索引位置为:3


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值