假设有2个整型数组:
list1[] = { 12, 8, 3, 5, 9, 2, 1, 0, 15, 17 };
list2[] = { 2, 3, 6, 9, 10, 12, 15, 17, 19, 27 };
首先,分2行输出这2个数组中的元素;
然后,提示用户输入要查找的整数,存放在变量n中;
接着,使用顺序查找法在list1中查找n,如果找到,输出其位置,如果没有,则提示用户:“该数值在list1中不存在”;
最后,使用二分查找法在list2中查找n,如果找到,输出其位置,如果没有,则提示用户:“该数值在list2中不存在”
list1 = [12, 8, 3, 5, 9, 2, 1, 0, 15, 17]
list2 = [2, 3, 6, 9, 10, 12, 15, 17, 19, 27]
# 输出两个数组的元素
print("list1: ", end="")
for i in list1:
print(i, end=" ")
print()
print("list2: ", end="")
for i in list2:
print(i, end=" ")
print()
# 提示用户输入要查找的整数
n = int(input("请输入要查找的整数:"))
# 在list1中使用顺序查找法查找n
position = -1
for i in range(len(list1)):
if list1[i] == n:
position = i
break
if position != -1:
print("在list1中的位置为:", position)
else:
print("该数值在list1中不存在")
# 在list2中使用二分查找法查找n
left, right = 0, len(list2) - 1
position = -1
while left <= right:
mid = (left + right) // 2
if list2[mid] == n:
position = mid
break
elif list2[mid] < n:
left = mid + 1
else:
right = mid - 1
if position != -1:
print("在list2中的位置为:", position)
else:
print("该数值在list2中不存在")
import java.util.*;
public class Main {
public static void main(String[] args) {
// 定义 list1 和 list2 两个整型数组
Integer[] list1 = {1, 3, 5, 6, 7, 8, 10, 20};
Integer[] list2 = {2, 4, 6, 8, 10, 12, 14, 16};
// 告知用户 list1 和 list2 中的元素
System.out.println("list1 中的元素:" + Arrays.toString(list1));
System.out.println("list2 中的元素:" + Arrays.toString(list2));
// 提示用户输入要查找的整数
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要查找的整数:");
int n = scanner.nextInt();
// 使用顺序查找法在 list1 中查找 n
int index = -1;
for (int i = 0; i < list1.length; i++) {
if (list1[i] == n) {
index = i;
break;
}
}
if (index != -1) {
System.out.println("该数值在 list1 中的位置为:" + index);
} else {
System.out.println("该数值在 list1 中不存在");
}
// 使用二分查找法在 list2 中查找 n
int start = 0;
int end = list2.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (list2[mid] == n) {
System.out.println("该数值在 list2 中的位置为:" + mid);
break;
} else if (list2[mid] > n) {
end = mid - 1;
} else {
start = mid + 1;
}
}
if (start > end) {
System.out.println("该数值在 list2 中不存在");
}
}
}