二分查找是针对有序的int数组,查找某数字在该数组的下标。
/** * 非递归实现方式 */ public static void getStrIndex(int[] iA, int i) { int minNum = 0; int maxNum = iA.length-1; int index = 0; while(minNum <= maxNum) { int mediant = (minNum+maxNum)/2; if (i == iA[mediant]) { index = mediant; break; } else if (i < iA[mediant]) { maxNum = mediant - 1; } else { minNum = mediant + 1; } } System.out.println("index="+index); }
/** * 递归实现方式 */ public static void recursionGet(int[] iA, int i, int minNum, int maxNum) { int index = 0; int mediant = (minNum+maxNum)/2; if (i == iA[mediant]) { index = mediant; System.out.println("index="+index); } else if (i < iA[mediant]) { recursionGet(iA, i, minNum, mediant - 1); } else { recursionGet(iA, i, mediant + 1, maxNum); } }