zoukankan      html  css  js  c++  java
  • Java入门:一些初学者需要掌握的基础算法程序——二分查找

    本例演示如何通过二分算法查找一个链表中的指定元素。

    import java.util.Scanner;
    class BinarySearchExample
    {
       public static void main(String args[])
       {
          int counter, num, item, array[], first, last, middle;
          //To capture user input
          Scanner input = new Scanner(System.in);
          System.out.println("Enter number of elements:");
          num = input.nextInt(); 
    
          //Creating array to store the all the numbers
          array = new int[num];
    
          System.out.println("Enter " + num + " integers");
          //Loop to store each numbers in array
          for (counter = 0; counter < num; counter++)
              array[counter] = input.nextInt();
    
          System.out.println("Enter the search value:");
          item = input.nextInt();
          first = 0;
          last = num - 1;
          middle = (first + last)/2;
    
          while( first <= last )
          {
             if ( array[middle] < item )
               first = middle + 1;
             else if ( array[middle] == item )
             {
               System.out.println(item + " found at location " + (middle + 1) + ".");
               break;
             }
             else
             {
                 last = middle - 1;
             }
             middle = (first + last)/2;
          }
          if ( first > last )
              System.out.println(item + " is not found.
    ");
       }
    }

    输出1(找到):

    Enter number of elements:
    7
    Enter 7 integers
    4
    5
    66
    77
    8
    99
    0
    Enter the search value:
    77
    77 found at location 4.

    输出2(没找到):

    Enter number of elements:
    5
    Enter 5 integers
    12
    3
    77
    890
    23
    Enter the search value:
    99
    99 is not found.
  • 相关阅读:
    C/C++常用的时间函数
    二维数组动态申请空间以及二维数组函数传参问题
    vc多线程编程
    [转载]_tmain main wmain WinMain
    using namespace std 解释
    [转载]C运行时库函数和API函数的区别和联系
    ZOJ 1013 Great Equipment(DP)
    c++ 运算符优先级表
    c语言输入的一些问题
    c\c++ 随机数函数
  • 原文地址:https://www.cnblogs.com/bayes/p/5344594.html
Copyright © 2011-2022 走看看