快速排序与二分查找的应用——判断号码是否中奖

本文介绍了一种利用快速排序对中奖号码进行升序排列的方法,并结合二分查找算法判断用户输入是否在序列中。通过示例展示了如何使用Java代码实现这一过程,以检测用户是否中奖。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有一个序列: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进行测试:
在这里插入图片描述
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值