Skip to content

Commit

Permalink
二分搜索
Browse files Browse the repository at this point in the history
  • Loading branch information
Xikl committed Apr 25, 2020
1 parent ef74e40 commit 5b44358
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.ximo.datastructuresinaction.algorithmsfourthedition.chapter01;

import java.util.Arrays;

/**
* @author xikl
* @date 2020/4/25
*/
public class BinarySearch {

public static int binarySearchByRecursive(int[] array, int key) {
if (array == null || array.length == 0) {
return -1;
}

// 排序
Arrays.sort(array);
return binarySearchByRecursive(array, key, 0, array.length);
}

/**
* 递归实现 二分搜索
*
* @param array
* @param key
* @param low
* @param high
* @return
*/
public static int binarySearchByRecursive(int[] array, int key, int low, int high) {
if (low > high) {
return -1;
}

// 优化 为了看懂 high + ((low - high) >> 1);
int mid = high + (low - high) / 2;

// 卫语句
if (key < array[mid]) {
return binarySearchByRecursive(array, key, low, mid - 1);
}

if (key > array[mid]) {
return binarySearchByRecursive(array, key, mid + 1, high);
}

// 那就是等于
return mid;
}


}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.ximo.datastructuresinaction.algorithmsfourthedition;
package com.ximo.datastructuresinaction.algorithmsfourthedition.chapter01;

/**
* @author xikl
* @date 2020/4/25
*/
public class Chapter01 {
public class IsPrime {

public static boolean isPrime(int n) {
// 大于1的数字才是
Expand Down Expand Up @@ -37,5 +37,4 @@ public static void main(String[] args) {
System.out.println(isPrime(13));
}


}

0 comments on commit 5b44358

Please sign in to comment.