Java入门:一些初学者需要掌握的基础算法程序——二分查找
2016-04-01 12:58
435 查看
本例演示如何通过二分算法查找一个链表中的指定元素。
输出1(找到):
输出2(没找到):
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.\n"); } }
输出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.
相关文章推荐
- java JDBC通用BaseDao升级版0.2
- JAVA JDBC通用BaseDao版0.1
- Openfire4.0.2源码部署到Eclipse
- MAVEN 工程打包resources目录外的更多资源文件
- java中Socket编程
- java集合的讲解
- JAVA·多线程:线程优先级
- springMVC4(2)请求映射全面分析
- 找不到或无法加载主类 com.sun.tools.javac.Main
- [JAVA · 初级]:14.数组
- 解析java中对象的"引用"
- Java处理java.util.ConcurrentModificationException异常
- 【撸码师的备忘录】 Java bean 与 xml 互相转化-JDK Marshaller
- 10分钟-JavaWeb入门-登陆功能实现
- maven中解决javax.servlet.jsp.PageContext cannot be resolved to a type
- sqoop.Sqoop: Got exception running Sqoop: java.lang.IllegalArgumentException: There is no column fou
- java中怎么把原始目录下的文件。复制到另外一个目录中,并且文件名不改掉
- java的守护线程与非守护线程
- Java入门:一些初学者需要掌握的基础算法程序——逆序输出
- Java单链表基本操作(六)--删除重复节点;