二分法如果没有找到的话,最后的结果出来后肯定是low-high=1
准备工作
public class Direct{
private int start;
private int end;
public Direct() {
this.start = -1;
this.end = -1;
}
public Direct(int start, int end) {
this.start = start;
this.end = end;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "{"start":""+this.start+"","end":""+this.end+""}";
}
}
1、二分法查找(数组默认是有序的)
public static boolean binarySearch(int[] arrays, int shu) {
if(arrays==null||arrays.length==0) {
return false;
}
int len = arrays.length;
int start =0;
int end = len - 1;
int temp = 0;
while(start<=end) {
temp = (start+end)/2;
if(arrays[temp]==shu) {
return true;
}else if(arrays[temp]<shu) {
start = temp + 1;
}else {
end = temp - 1;
}
}
return false;
}
2、查找大于等于给定数的数组的下标(数组默认从小到大排序的)
public static Direct binarySearch(int[] arrays, int shu) {
if(arrays==null||arrays.length==0) {
System.out.println("不合法!");
return new Direct(-1,-1);
}
int len = arrays.length;
int start = 0;
int end = len - 1;
int temp = 0;
while(start<=end) {
temp = (start+end)/2;
if(arrays[temp]<shu){
start = temp + 1;
}else {
end = temp - 1;
}
}
if(start==len) {
System.out.println("数组中的数都小于指定的数!");
}else if(end==-1){
System.out.println("数组中的数都大于等于指定的数!");
}else {
System.out.println("成功找到!");
}
return new Direct(start, end);
//这里的start就是大于等于指定数的数组的下标;end就是小于指定数的数组的下标
}
3、查找大于指定数的数组的下标(数组默认从小到大排序的)
public static Direct binarySearch(int[] arrays, int shu) {
if(arrays==null||arrays.length==0) {
System.out.println("不合法!");
return new Direct(-1,-1);
}
int len = arrays.length;
int start = 0;
int end = len - 1;
int temp = 0;
while(start<=end) {
temp = (start+end)/2;
if(arrays[temp]<=shu){
start = temp + 1;
}else {
end = temp - 1;
}
}
if(start==len) {
System.out.println("数组中的数都小于等于指定的数!");
}else if(end==-1){
System.out.println("数组中的数都大于指定的数!");
}else {
System.out.println("成功找到!");
}
return new Direct(start, end);
//这里的start就是大于指定数的数组的下标;end就是小于等于指定数的数组的下标
}
4、寻找旋转数组中的最小值(无重复元素)
class Solution {
public int findMin(int[] nums) {
int l = 0;
int h = nums.length - 1;
while(l < h){
int m = l + (h-l)/2;
if(nums[m] > nums[h]){
l = m + 1;
}else if(nums[m]<nums[h]){
h = m;
}else{
//这种情况不存在
}
}
return nums[h];
}
}
4、寻找旋转数组中的最小值(有重复元素)
class Solution {
public int findMin(int[] nums) {
int l = 0;
int h = nums.length - 1;
while(l < h){
int m = l + (h-l)/2;
if(nums[m] > nums[h]){
l = m + 1;
}else if(nums[m]<nums[h]){
h = m;
}else{
h = h - 1;
}
}
return nums[h];
}
}
5、寻找峰值
class Solution {
public int findPeakElement(int[] nums) {
int len = nums.length;
int start = 0;
int end = len - 1;
int middle = 0;
while(start<end){
middle = (end+start)/2;
if(nums[middle]<nums[middle+1]){
start = middle + 1;
}else if(nums[middle]>nums[middle+1]){
end = middle;
}else{
//此情况不存在
}
}
return start;
}
}