Skip to content

Commit f1f9485

Browse files
committed
修正算法错误
感谢用户反馈指出我们的问题
1 parent 6927c7e commit f1f9485

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

Chapter3/Chapter3.md

+19-15
Original file line numberDiff line numberDiff line change
@@ -30,22 +30,26 @@ public static int sequentialSerach(int[] elements, int target){
3030
如果比我们想要的小,我们就在右边搜索。然后在缩小后的搜索范围查看判断后数组中间的数,就这样依次进行下去,直到找到结果或者全部搜索完成。不过,利用二进制搜索的数组必须是排列好的,否则比如先排序才行。
3131

3232
```java
33-
/*
34-
@param elements an array containing the items to be sorted.
35-
36-
Postcondition: elements contains its original items and items
37-
in elements are sorted in ascending order.
38-
*/
39-
public static void insertionSort(int[] elements){
40-
for(int j = 1; j< elements.length; j++){
41-
int temp = elements[j];
42-
int possibleIndex = j;
43-
while(possibleIndex > 0 && temp < elements[possibleIndex - 1]){
44-
elements[possibleIndex] = elements[possibleIndex - 1];
45-
possibleIndex --;
46-
}
47-
elements[possibleIndex] = temp;
33+
/***
34+
@param elements. an array containing the items to be searched.
35+
Precondition: items in elements are sorted in ascending order.
36+
@param target. the item to be found in elements.
37+
@return an index of target in elements if target found; -1 otherwise.
38+
***/
39+
public static int binarySearch(int[] elements, int target){
40+
int left = 0;
41+
int right = elemetns.length -1 ;
42+
while (left <= right){
43+
int middle (left + right)/2;
44+
if (targetr < elements[middle]
45+
right =middle-1;
46+
else if (target> elements[middle])
47+
left = middle +1;
48+
else
49+
return middle
50+
4851
}
52+
return -1;
4953
}
5054
```
5155

0 commit comments

Comments
 (0)