使用循環實現&使用遞歸實現java
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); } } }
樹表查找,包括二叉搜索樹的構建與元素查找;spring
package com.pt.spring.learn.bean; /** * 二叉查找樹: * 某節點若是左子樹不爲空,左子樹上全部節點的值都小於該節點的值 * 若是右子樹不爲空,右子樹上全部節點的值都大於該節點的值 * 左右子樹也都是二叉查找樹 */ public class BinarySearchTree { public static void main(String[] args) { System.out.println("-----start run----"); int[] array = new int[]{8, 6, 9, 7, 1, 3, 5}; //構建二叉查找樹 Node root = null; for (int i = 0; i < array.length; i++) { root = insert(root, array[i]); } System.out.println(root); //查找 Node get = searchNode(root, 90); System.out.println(get); } static Node searchNode(Node root, int data) { if (root == null) { return null; } if (root.value == data) { return root; } if (root.value > data) { return searchNode(root.leftNode, data); } else { return searchNode(root.rightNode, data); } } static Node insert(Node root, int data) { if (root == null) { return new Node(data); } if (root.value >= data) { root.leftNode = insert(root.leftNode, data); } else { root.rightNode = insert(root.rightNode, data); } return root; } static class Node { Integer value; Node leftNode; Node rightNode; public Node(Integer value) { this.value = value; } @Override public String toString() { return "{" + "\"value\":" + value + ", \"leftNode\":" + leftNode + ", \"rightNode\":" + rightNode + '}'; } } }