File tree 1 file changed +19
-15
lines changed
1 file changed +19
-15
lines changed Original file line number Diff line number Diff line change @@ -30,22 +30,26 @@ public static int sequentialSerach(int[] elements, int target){
30
30
如果比我们想要的小,我们就在右边搜索。然后在缩小后的搜索范围查看判断后数组中间的数,就这样依次进行下去,直到找到结果或者全部搜索完成。不过,利用二进制搜索的数组必须是排列好的,否则比如先排序才行。
31
31
32
32
``` 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
+
48
51
}
52
+ return - 1 ;
49
53
}
50
54
```
51
55
You can’t perform that action at this time.
0 commit comments