栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > Java面试题

介绍一下java中的二分法运用

Java面试题 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

介绍一下java中的二分法运用

public class Test {
public static void main(String[] args) {
// 定义一个数组
int nums[] = { 1, 3, 6, 8, 9, 10, 12, 18, 20, 33, 34 };
// 欲查询的数字
int num = 35;
// 输出num在nums中的索引
System.out.println(“二分法查看数组中某数的索引为:” + dichotomy(nums, num));
}


public static int dichotomy(int[] nums, int num) {
// 数组长度必须大于零
if (nums != null && nums.length > 0) {

// 开始索引
int start = 0;
// 结束索引
int end = nums.length – 1;
// 中间索引
int center = (start + end) / 2;

// 开始索引不能大于结束索引
while (start <= end) { // 取中间索引值比较,如果相同,返回该索引 if (num == nums[center]) { return center; } // 如果值在center右边或左边,重新定位start或end,重新计算center值 if (num > nums[center]) {
start = center + 1;
}

if (num < nums[center]) { end = center - 1; } center = (start + end) / 2; } } return -1;}}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/264712.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号