线性表查找(顺序查找和折半查找以及代码实现)

顺序查找

  • 存储结构可以使顺序表,也可以是链表
  • 逐个比较查询,找到返回数据或者索引,没找到返回null
  • 在各个节点查找概率相同的情况下,默认查询长度为一半长度,时间复杂度T(n) = O(n)
public static void main(String[] args) {
		int [] scoreArr = {89, 45, 78, 45, 100, 98 ,86, 100, 65};
		int score = 100;
		int index = search(scoreArr, score);
		if (index == -1) {
			System.out.println("分数不存在");
		}else {
			System.out.println(score + "的索引是" + index);
		}
	}
	
	public static int search(int [] arr, int key) {
		int index = -1;
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] == key) {
				index = i;
				break;
			}
		}
		return index;
	}

折半查找

  • 又称二分查找,这种查找需要表满足两个条件
  • 必须使用顺序存储结构
  • 查找表必须按关键字大小有序排列
    线性表查找(顺序查找和折半查找以及代码实现)_第1张图片
public static void main(String[] args) {
		int [] array = {1, 2, 3, 4, 5, 6, 7, 8, 9,10};
		int key = 10;
		int index = binarySearch(array, key);
		if (index == -1) {
			System.out.println("不存在");
		}else {
			System.out.println(key + "的索引是" + index);
		}
	}
	
	public static int binarySearch(int[] array, int key) {
		int low = 0;
		int high = array.length-1;
		while (low <= high) {
			int mid = (low + high) / 2;
			if (key == array[mid]) {
				return mid;
			}else if (key < array[mid]) {
				high = mid - 1;
			}else {
				low = mid + 1;
			}
		}
		return -1;
	}
// 递归实现这般查找
public static void main(String[] args) {
		int [] array = {1, 2, 3, 4, 5, 6, 7, 8, 9,10};
		int key = 10;
		int index = binarySearch(array, key);
		if (index == -1) {
			System.out.println("不存在");
		}else {
			System.out.println(key + "的索引是" + index);
		}
	}
	
	public static int binarySearch(int[] array, int key) {
		int low = 0;
		int high = array.length-1;
		return binarySearch(array, key, low, high);
	}
	
	public static int binarySearch(int[] array, int key, int low, int high) {
		if (low > high) {
			return -1;
		}
		int mid = (low + high) / 2;
		if (key == array[mid]) {
			return mid;
		}else if (key < array[mid]) {
			return binarySearch(array, key, low, mid-1);
		}else {
			return binarySearch(array, key, mid+1, high);
		}
	}

你可能感兴趣的:(#,数据结构)