java查找

1、直接查找

    /*
	 * 直接查找,数组可以无序
	 */
	private static int dirSeach(int[] arr, int index) {
		//r记录找到的索引,-1索引表示没找到,找到返回对应索引
		int r = -1;
		//遍历整个数据
		for (int i = 0; i < arr.length; i++) {
			//如果找到,把索引赋给r,退出遍历
			if (arr[i] == index) {
				r = i;
				break;
			}
		}
		//把对应索引返回
		return r;
	}

2、折半查找

/*
	 * 折半查找非递归,必须是有序数组
	 */
	private static int banarySearch(int[] a, int index) {
		int low = 0;
		int high = a.length-1;
		int mid;
		while (low <= high) {
			mid = (high + low) / 2;
			if (a[mid] == index) {
				//找到返回mid索引
				return mid;
			}
			// index比a[mid]小,说明在左部
			else if (index < a[mid]) {
				high = mid - 1;
			}
			// index比a[mid]大,说明在右边
			else {
				low = mid + 1;

			}
		}
		//没找到返回-1
		return -1;
	}
发布了41 篇原创文章 · 获赞 1 · 访问量 4729

猜你喜欢

转载自blog.csdn.net/tomorrow_shoe/article/details/96372373