怕什么真理无穷,进一寸有进一寸的欢喜
1.二分查找
public int binarySearch(int[] arr,int key){
int low = 0;
int high = arr.length - 1;
int mid = 0;
if(key>arr[high]||key<arr[low]||low>high){
return -1;
}
while(low<=high){
mid = (low + high)/2;
if(arr[mid] > key){
high = mid - 1;
}else if(arr[mid] < key){
low = mid +1;
}else {
return mid;
}
}
return -1;
}
2.快速排序
public void quickSort(int[] arr,int low,int high){
int start = low;
int end = high;
int key = arr[low];
while(start < end){
//从后向前找
while(start < end && arr[end] >= key){
end--;
}
//交换arr-end和arr-start
if(arr[end] >= key){
int temp = arr[end];
arr[end] = arr[start];
arr[start] = temp;
}
//从前向后找
while(start < end && arr[start] <= key){
start++;
}
//交换
if(arr[start] >= key){
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
}
//递归
if(start > low){
quickSort(arr,low,start-1);
}
if(end < high){
quickSort(arr,end+1,high);
}
}
3.二叉树的层次遍历
public void LaywerTraversal(TreeNode root){
if(root==null){
return;
}
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
list.add(root);
TreeNode temp;
while (!list.isEmpty()){
temp = list.poll();
System.out.println(temp.val);
if(temp.left != null){
list.add(temp.left);
}
if(temp.right!=null){
list.add(temp.right);
}
}
}
4.蛇形打印二叉树
public void snakePrint(TreeNode root){
if(root == null){
return;
}
//用2个栈解决
Li