面试算法代码知识梳理系列
一、概要
本文介绍了有关二分查找的算法的Java代码实现,所有代码均可通过 在线编译器 直接运行,算法目录:
普通二分查找
查找关键字第一次出现的位置
查找关键字最后一次出现的位置
查找小于关键字的最大数字出现的位置
查找大于关键字的最小数字出现的位置
对于二分查找,有以下几个需要注意的点:
将pStart或pEnd修改的条件进行合并.
如果出现了pEnd=pMid的情况要将while条件修改为pStart
如果出现了pStart=pMid的情况要将while条件修改为pStart
对于pStart
对于pStart
二、代码实现
2.1 普通二分查找
实现代码
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));
}
}
2.2 查找关键字第一次出现的位置
实现代码
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));
}
}
2.3 查找关键字最后一次出现的位置
实现代码
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));
}
}
2.4 查找小于关键字的最大数字出现的位置
代码实现
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));
}
}
2.5 查找大于关键字的最小数字出现的位置
代码实现
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));
}
}
更多文章,欢迎访问我的 Android 知识梳理系列: