有一个序列:8,4,20,100,23,34,12,88,66,9。从键盘中任意输入一个数据,判断序列中是否包含此数,如果包含则提示用户中奖
先通过快速排序,将中奖号码按照升序排列
public static void quickSort(int[] arr, int low, int high) {
// 快速排序
if (low < high) {
int index = getIndex(arr, low, high);//找寻基准元素的正确索引
quickSort(arr, low, index - 1);//对基准元素前的序列进行排序
quickSort(arr, index + 1, high);对基准元素后的序列进行排序
}
}
public static int getIndex(int[] arr, int low, int high) {
// 基准元素
int temp = arr[low];
while (low < high) {
// 当队尾元素大于等于基准元素时,向前挪动high指针
while (low < high && arr[high] >= temp) {
high--;
}
// 如果队尾元素小于temp,需要将其赋值给low
arr[low] = arr[high];
// 当队尾元素大于temp时,向前挪动low指针
while (low < high && arr[low] <= temp) {
low++;
}
// 当队首元素大于temp时,需要将其赋值给high
arr[high] = arr[low];
}
// 当low和high相等跳出循环,此时的low或high就是temp的正确索引位置
// low位置的值并不是temp,所以需要将temp赋值给arr[low]
arr[low] = temp;
return low;// 返回基准元素位置
}
再通过二分查找,判断输入的号码是否中奖
public static int binarysearch(int arr[], int n, int key) {
// 折半查找
int low = 0, high = n - 1, mid;
if (arr[low] == key)
return low;
if (arr[high] == key)
return high;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == key)
return mid;// 查找成功,返回mid
if (key > arr[mid])
low = mid + 1;// 在后半序列中查找
else
high = mid - 1;// 在前半序列中查找
}
return -1;// 查找失败,返回-1
}
最后通过main()方法提示中奖信息
public static void main(String[] args) {
int[] arr = { 8, 4, 20, 100, 23, 34, 12, 88, 66, 9 };
quickSort(arr, 0, arr.length - 1);
System.out.print("中奖号码:");
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
System.out.println();
Scanner sc = new Scanner(System.in);
System.out.print("请输入要查询的号码:");
int n = sc.nextInt();
if (binarysearch(arr, arr.length, n) == -1) {
System.out.println("很遗憾,未中奖!");
} else
System.out.println("恭喜你,中奖了!");
}
以66和67进行测试: