顺序查找
最简单的从头开始对比查找。
折半查找
- 要求:有序数组
- 思想:将n个元素分成大致相同的两半,取中值和值x比较,如果相等则找到,如果值x小于中值,则只在数组的左半部分继续搜索值x;如果值x大于中值,则只在数组右半部分继续搜索值x
- 复杂度:最坏情况下需要O(logN)时间
- 代码如下:
int binarySearch(int arr[], int x, int len){
int left = 0, right = len-1;
while(left <= right){
int mid = (left + right) / 2;
if(x == arr[mid]){
return mid;
}
if(x > arr[mid]){
left = mid + 1;
}else{
right = mid -1;
}
}
return -1;
}
哈希查找
时间复杂度为O(1)
索引查找
二叉树
二叉树的前序遍历、中序遍历、后序遍历测试代码如下:
package com.tree;
public class Tree{
public static void preOrder(TreeNode node){
if(node == null){
return ;
}
System.out.print(node.getData());
preOrder(node.getLeft());
preOrder(node.getRight());
}
public static void midOrder(TreeNode node){
if(node == null){
return ;
}
preOrder(node.getLeft());
System.out.print(node.getData());
preOrder(node.getRight());
}
public static void postOrder(TreeNode node){
if(node == null){
return ;
}
preOrder(node.getLeft());
preOrder(node.getRight());
System.out.print(node.getData());
}
public static void main(String[] args){
TreeNode root = new TreeNode("A");
TreeNode nodeB = new TreeNode("B");
TreeNode nodeC = new TreeNode("C");
TreeNode nodeD = new TreeNode("D");
TreeNode nodeE = new TreeNode("E");
TreeNode nodeF = new TreeNode("F");
root.setLeft(nodeB);
root.setRight(nodeC);
nodeB.setLeft(nodeD);
nodeB.setRight(nodeE);
nodeC.setLeft(nodeF);
System.out.print("先序遍历");
preOrder(root);
System.out.print("中序遍历");
midOrder(root);
System.out.print("后序遍历");
postOrder(root);
}
}
程序运行及结果如下(修改了控制台字体使得中文乱码):