本文介绍了有关二分查找的算法的Java
代码实现,全部代码都可经过 在线编译器 直接运行,算法目录:java
对于二分查找,有如下几个须要注意的点:面试
pStart
或pEnd
修改的条件进行合并.pEnd=pMid
的状况要将while
条件修改成pStart<pEnd
pStart=pMid
的状况要将while
条件修改成pStart<pEnd-1
pStart<pEnd
的结束条件,最后一次进入循环的数组长度为2
,结束时数组长度为1
pStart<pEnd-1
的结束条件,最后一次进入循环的数组长度为3
,结束时数组长度为1
或2
class Untitled {
static int binNormalSearch(int p[], int len, int key) {
int start = 0;
int end = len-1;
while (start <= end) {
int mid = (start+end) >> 1;
if (p[mid] > key) {
end = mid-1;
} else if (p[mid] < key) {
start = mid+1;
} else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int p[] = {1, 5, 6, 7, 11, 11, 56};
System.out.println("index=" + binNormalSearch(p, p.length, 11));
}
}
复制代码
class Untitled {
static int binFirstKSearch(int p[], int len, int key) {
int start = 0;
int end = len-1;
while (start < end) {
int mid = (start+end) >> 1;
if (p[mid] > key) {
end = mid-1;
} else if (p[mid] < key) {
start = mid+1;
} else {
end = mid;
}
}
if (p[start] == key) {
return start;
}
return -1;
}
public static void main(String[] args) {
int p[] = {1, 5, 6, 7, 11, 11, 11, 11, 56};
System.out.println("index=" + binFirstKSearch(p, p.length, 11));
}
}
复制代码
class Untitled {
static int binLastKSearch(int p[], int len, int key) {
int start = 0;
int end = len-1;
while (start < end-1) {
int mid = (start+end) >> 1;
if (p[mid] > key) {
end = mid-1;
} else if (p[mid] < key) {
start = mid+1;
} else {
start = mid;
}
}
if (p[end] == key) {
return end;
}
if (p[start] == key) {
return start;
}
return -1;
}
public static void main(String[] args) {
int p[] = {1, 5, 6, 7, 11, 11, 11, 11, 56};
System.out.println("index=" + binLastKSearch(p, p.length, 11));
}
}
复制代码
class Untitled {
static int binMaxLessKSearch(int p[], int len, int key) {
int start = 0;
int end = len-1;
while (start < end-1) {
int mid = (start+end) >> 1;
if (p[mid] > key) {
end = mid-1;
} else if (p[mid] < key) {
start = mid;
} else {
end = mid-1;
}
}
if (p[end] < key) {
return end;
}
if (p[start] < key) {
return start;
}
return -1;
}
public static void main(String[] args) {
int p[] = {1, 5, 6, 7, 11, 11, 11, 11, 56};
System.out.println("index=" + binMaxLessKSearch(p, p.length, 11));
}
}
复制代码
class Untitled {
static int binMinMoreKSearch(int p[], int len, int key) {
int start = 0;
int end = len-1;
while (start < end) {
int mid = (start+end) >> 1;
if (p[mid] > key) {
end = mid;
} else if (p[mid] < key) {
start = mid+1;
} else {
start = mid+1;
}
}
if (p[start] > key) {
return start;
}
return -1;
}
public static void main(String[] args) {
int p[] = {1, 5, 6, 7, 11, 11, 11, 11, 56};
System.out.println("index=" + binMinMoreKSearch(p, p.length, 11));
}
}
复制代码