标签:end 递归 new ack util imp import param deque
使用循环实现&使用递归实现
package com.pt.spring.learn.bean; import java.util.ArrayDeque; import java.util.Queue; public class BinFind { public static void main(String[] args) { int[] array = new int[]{1, 2, 3, 4, 5, 7, 8, 9, 10}; System.out.println(binFind(array, 0, 8, 8)); System.out.println(binSearchLoop(array, 0, 8, 9)); } public static int binSearchLoop(int[] array, int startIndex, int endIndex, int objectValue) { Queue<int[]> paramsQueue = new ArrayDeque<>(); paramsQueue.add(new int[]{startIndex, endIndex}); while (!paramsQueue.isEmpty()) { int[] tmpParams = paramsQueue.poll(); startIndex = tmpParams[0]; endIndex = tmpParams[1]; if (objectValue > array[endIndex] || objectValue < array[startIndex] || startIndex > endIndex) { return -1; } if (startIndex == endIndex && array[endIndex] != objectValue) { return -1; } int mid = (startIndex + endIndex) / 2; if (array[mid] == objectValue) { return mid; } if (array[mid] > objectValue) { paramsQueue.add(new int[]{startIndex, mid}); } else { paramsQueue.add(new int[]{mid + 1, endIndex}); } } return -1; } public static int binFind(int[] array, int startIndex, int endIndex, int objectValue) { if (objectValue > array[endIndex] || objectValue < array[startIndex] || startIndex > endIndex) { return -1; } if (startIndex == endIndex && array[endIndex] != objectValue) { return -1; } int mid = (startIndex + endIndex) / 2; if (array[mid] == objectValue) { return mid; } if (array[mid] > objectValue) { return binFind(array, startIndex, mid, objectValue); } else { return binFind(array, mid + 1, endIndex, objectValue); } } }
标签:end 递归 new ack util imp import param deque
原文地址:https://www.cnblogs.com/tengpan-cn/p/9886337.html