前几天去面试,让我写二分查找法,真是哔了狗!
提了离职申请,没事写写吧!
首先二分查找是在一堆有序的序列中找到指定的结果。
public class Erfen
{
public static int erfen(int a[], int key)
{
int start = 0;
int end = a.length;
while (start < end)
{
int mid = (start + end) / 2; if (key == a[mid])
{
System.out.println("@@");
return mid; }
else if (key < a[mid])
{
end = mid - 1;
System.out.println(mid + "$$" + end);
}
else
{
start = mid + 1;
System.out.println("&&");
}
}
return -1; } public static int digui(int a[], int start, int end, int key)
{
if (start < end)
{
int mid = (start + end) / 2;
if (key == a[mid])
{
return mid;
}
else if (key < a[mid])
{
digui(a, start, mid - 1, key);
}
else
{
digui(a, mid + 1, end, key);
}
} return -1;
} public static void main(String[] args)
{
int[] a = { 1, 2, 3, 6, 8, 9 };
System.out.println(a.length);
int re = Erfen.erfen(a, 6);
System.out.println(re); int ret = Erfen.digui(a, 0, 6, 6);
System.out.println(ret);
} }