Skip to content

Commit a01cdc6

Browse files
author
mj
committed
二分查找demo
1 parent b5665d5 commit a01cdc6

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

app/src/main/java/com/mj/android_note/data_structure/DataStructureDemo.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
import androidx.annotation.NonNull;
66

7+
import com.mj.android_note.data_structure.algorithm.binary.BinarySearchUtils;
8+
79
import java.util.ArrayList;
810
import java.util.HashMap;
911
import java.util.Iterator;
@@ -74,6 +76,10 @@ public static void main(String[] args) {
7476
// 3.LinkedHashMap是如何保证按照访问顺序,将数据存在链表的尾部的。
7577
// 4.HashMap中的entrySet是何拿值的
7678

79+
// 二分查找测试
80+
int[] sortArray = {1, 2, 3, 4, 5, 6, 8, 10, 100, 111, 126};
81+
int i = BinarySearchUtils.binarySearch(sortArray, 100);
82+
printLog("binary search target index : " + i);
7783
}
7884

7985
private static void printMap(Map<String, Integer> map) {
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.mj.android_note.data_structure.algorithm.binary;
2+
3+
/**
4+
* Author : MJ
5+
* Date : 2020-03-17--13:53
6+
7+
* Description : 二分查找法
8+
*/
9+
public class BinarySearchUtils {
10+
11+
/**
12+
* 二分查找
13+
*
14+
* @param array 给定一个数组
15+
* @param target 目标值要找的目标值
16+
* @return 目标值在数组中的索引
17+
*/
18+
public static int binarySearch(int[] array, int target) {
19+
int startIndex = 0;
20+
int endIndex = array.length - 1;
21+
int searchCount = 0;
22+
while (startIndex <= endIndex) {
23+
int midIndex = (startIndex + endIndex) / 2;
24+
int val = array[midIndex];
25+
searchCount++;
26+
if (target > val) {
27+
startIndex = midIndex + 1;
28+
} else if (target < val) {
29+
endIndex = midIndex - 1;
30+
} else {
31+
System.out.println("search count : " + searchCount);
32+
return midIndex;
33+
}
34+
}
35+
return ~startIndex;
36+
}
37+
}

0 commit comments

Comments
 (0)