eg1
package Fri;
public class Fri04 {
public static void main(String[] args) {
int[] num= {1,2,3,4,5,6,7,8,9};
int target=4;
int index=-1;
int low=0,high=num.length-1;
while(low<=high) {
//求中间数
int mid=(low+high)/2;
//判断中间数与目标值是否相等
if(num[mid]==target) {
index=mid;
break;
}
if(num[mid]<target) {
low=mid+1;
index=low;
break;
}
if(num[mid]>target) {
high=mid-1;
index=high;
break;
}
}
System.out.println(index);
}
}
eg2
package Fri;
import java.util.Arrays;
public class Fri05 {
public static void main(String[] args) {
String[] contact = { "Megatron", "s司马铁锤", "Laden", "angelababy", "b比尔盖饭", "I林平之", "BIGBANG", "Adele Adkins",
"m马云", "Gaddafi", "郭德纲", "m马伯庸", "Ma Tong Seok" };
String target = "m马云";
//方法一
// int index=Arrays.binarySearch(contact, target);
// System.out.println(index);
//方法二
int low = 0, high = contact.length - 1;
int index = -1;
Arrays.sort(contact);
System.out.println(Arrays.toString(contact));
while (low <= high) {
int mid = (low + high) >> 1;
if (contact[mid].compareTo(target) == 0) {
index = mid;
break;
}
if (contact[mid].compareTo(target) > 0) {
low = mid - 1;
index = low;
break;
}
if (contact[mid].compareTo(target) < 0) {
low = mid + 1;
index = high;
break;
}
}
System.out.println(index);
}
}
eg3
package Fri;
public class eg2 {
// 使用二分查找法,查找有序数组keys中指定字符target的下标位置。
// 字符数组
public static void main(String[] args) {
char[] keys = { 'a', 'b', 'd', 'f', 'h', 'k', '1', 'm', 'n', 'w' };
// 目标字符
char target = 'f';
int index = -1;
int low = 0, high = keys.length - 1;
while(low<=high) {
int mid=(low+high)/2;
if(keys[mid]==target) {
break;
}
else if(keys[mid]<target) {
low=mid+1;
index=low;
break;
}
else if(keys[mid]>target) {
high=mid-1;
index=high;
break;
}
}
System.out.println(index);
}
}
eg4
package Fri;
//使用双指针遍历,查找无序数组phoneNumberArray中指定字符串target的下标位置。
import java.util.Scanner;
public class eg1 {
public static void main(String[] args) {
// 手机尾号数组
String[] phoneNumberArray = { "4392", "9961", "1794", "4431", "9433", "2784", "8961", "9981", "3391", "3967",
"3721" };
// 目标尾号
try (Scanner input = new Scanner(System.in)) {
String target = input.next();
int index = -1;
for (int i = 0, k = phoneNumberArray.length-1; i <= k; i++, k--) {
if (phoneNumberArray[i] == target) {
index = i;
break;
}
if (phoneNumberArray[k] == target) {
index = k;
break;
}
}
System.out.println(index);
}
}
}