二分查找


public class BinaryResearch {
	public static int binarySearch(int[] a, int key) {
		int max, min, mid;
		max = a.length - 1;
		min = 0;
		mid = (max + min) / 2;
		while (key != a[mid]) {
			if (key > a[a.length - 1] || key < a[0]) {
				return -1;
			}
			if (key == a[min]) {
				return min + 1;
			}
			if (key == a[max]) {
				return max + 1;
			}
			if (key < a[mid]) {
				max = mid;
				mid = (max + min) / 2;
			} else if (key > a[mid]) {
				min = mid;
				mid = (max + min) / 2;
			}
		}
		return mid + 1;
	}

	public static int binarySearch(float[] a, float key) {
		int max, min, mid;
		max = a.length - 1;
		min = 0;
		mid = (max + min) / 2;
		while (key != a[mid]) {
			if (key > a[a.length - 1] || key < a[0]) {
				return -1;
			}
			if (key == a[min]) {
				return min + 1;
			}
			if (key == a[max]) {
				return max + 1;
			}
			if (key < a[mid]) {
				max = mid;
				mid = (max + min) / 2;
			} else if (key > a[mid]) {
				min = mid;
				mid = (max + min) / 2;
			}
		}
		return mid + 1;
	}

	public static int binarySearch(double[] a, double key) {
		int max, min, mid;
		max = a.length - 1;
		min = 0;
		mid = (max + min) / 2;
		while (key != a[mid]) {
			if (key > a[a.length - 1] || key < a[0]) {
				return -1;
			}
			if (key == a[min]) {
				return min + 1;
			}
			if (key == a[max]) {
				return max + 1;
			}
			if (key < a[mid]) {
				max = mid;
				mid = (max + min) / 2;
			} else if (key > a[mid]) {
				min = mid;
				mid = (max + min) / 2;
			}
		}
		return mid + 1;
	}
	public static void main(String[] args) {
		BinaryResearch search = new BinaryResearch();
		int[] a = { 1,3,4,5, 6, 7, 8, 19,25 };
		int i = search.binarySearch(a,25);
		System.out.println(i);
		float b[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };
		int j=search.binarySearch(b, 4.0f);
		System.out.println(j);
	}
}







你可能感兴趣的:(J#)