public class Entry {
public static void main(String[] args) {
// 定义奖项数组,并为其设置值
Awards[] awards = new Awards[4] ;
awards[0] = new Awards("一等奖" , 1) ;
awards[1] = new Awards("二等奖" , 2) ;
awards[2] = new Awards("三等奖" , 3) ;
awards[3] = new Awards("谢谢惠顾" , 4) ;
// 补全代码
Random r = new Random();
for (int j = 0; j < 100; j++) {
int i = r.nextInt(9);
String name = binarySearch(awards, i).getName();
System.out.println("恭喜您!" + name);
}
}
// 二分查找实现
public static Awards binarySearch(Awards[] awards , int num) {
int leftIndex = 0;
int totalWeight = 0;
for (int i = 0; i < awards.length; i++) {
int weight = awards[i].getWeight();
totalWeight += weight;
}
int rightIndex = totalWeight - 1;
while (leftIndex <= rightIndex){
int midIndex = (leftIndex + rightIndex) / 2;
if(midIndex > num){
rightIndex = midIndex - 1;
}else if (midIndex < num){
leftIndex = midIndex + 1;
}else {
switch (num){
case 0:
return awards[0];
case 1:
case 2:
return awards[1];
case 3:
case 4:
case 5:
return awards[2];
case 6:
case 7:
case 8:
case 9:
return awards[3];
}
}
}
return null;
}
}
?????
最新推荐文章于 2024-09-25 10:59:43 发布