二分法、
问题
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
注意:假设数组中无重复元素。
代码实现
package com.song.always;
public class TestCode {
public static void main(String[] args) {
int[] nums = {1, 3, 5, 7, 9, 11};
int target = 10;
int indexValue = searchIndex(nums, target);
System.out.println("输出的结果:{}" + indexValue);
}
public static int searchIndex(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int mid = 0;
while (left <= right) {
mid = (left + right) / 2;
if (target == nums[mid]) {
return mid;
} else if (target > nums[mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
System.out.println("mid :{}" + mid);
if (target > nums[mid]) {
return mid + 1;
} else {
return mid;
}
}
}