zoukankan      html  css  js  c++  java
  • 折半算法

    算法要求:数组序列呈线性结构。

    首先设置三个变量low,mid,height,分别保存数组元素的开始,中间,末尾的序号。假定有100个元素,开始时令low=0,height=99;mid=(low+height)/2,接着进行判断:

    (1)若序号为mid的数组元素值等于查找数,则返回mid。

    (2)若序号为mid的数组元素的值大于查找数,则令height=mid-1。

    (3)若序号为mid的数组元素的值小于查找数,则令low=mid+1。

    代码段:

    import java.util.*;

    public class Yin {
    static final int N=100;
    public static int show(int []a, int m, int x) {
    int low,height,mid;
    low=1;
    height=m;
    while(low<=height) {
    mid=(low+height)/2;
    if(x==a[mid]) {
    return mid;
    }
    else if(x<a[mid]) {
    height=mid-1;
    }
    else if(x>a[mid]) {
    low=mid+1;
    }
    }
    return -1;

    }
    public static void main(String[] args) {
    int[] shuzu = new int[N];
    int b,p;
    for(int i=1;i<N;i++) {
    shuzu[i]=i;
    }
    System.out.println("请输入要查找的数");
    Scanner scan = new Scanner(System.in);
    b=scan.nextInt();
    p=show(shuzu,N,b);
    System.out.println(b+ "的位置为" +p);
    }
    }

  • 相关阅读:
    linux日常。
    tp5中的config类和config助手函数
    TP5隐藏index.php
    TP5读取数据概述
    TP5的安装部署概要
    eclipse4.7中文包安装方法。
    利用mysqldump备份magento数据库
    MySQL 基础知识
    PHP 基础知识
    妖怪与和尚过河问题
  • 原文地址:https://www.cnblogs.com/mianyang0902/p/10626245.html
Copyright © 2011-2022 走看看