彩票走势图

折半查找(二分查找)的递归和非递归算法

原创|其它|编辑:郝浩|2009-10-20 11:32:57.000|阅读 2122 次

概述:本文介绍了折半查找(二分查找)的递归和非递归算法。

# 慧都年终大促·界面/图表报表/文档/IDE等千款热门软控件火热促销中 >>

  /**
  *名称:BinarySearch
  *功能:实现了折半查找(二分查找)的递归和非递归算法.
  *说明:
  * 1、要求所查找的数组已有序,并且其中元素已实现Comparable接口,如Integer、String等.
  * 2、非递归查找使用search();,递归查找使用searchRecursively();
  *
  *本程序仅供编程学习参考
  */
  class BinarySearch> {
  private T[] data;//要排序的数据
  public BinarySearch(T[] data){
  this.data = data;
  }
  public int search(T key){
  int low;
  int high;
  int mid;
  if(data == null)
  return -1;
  low = 0;
  high = data.length - 1;
  while(low <= high){
  mid = (low + high) / 2;
  System.out.println("mid " + mid + " mid value:" + data[mid]);///
  if(key.compareTo(data[mid]) < 0){
  high = mid - 1;
  }else if(key.compareTo(data[mid]) > 0){
  low = mid + 1;
  }else if(key.compareTo(data[mid]) == 0){
  return mid;
  }
  }
  return -1;
  }
  private int doSearchRecursively(int low , int high , T key){
  int mid;
  int result;
  if(low <= high){
  mid = (low + high) / 2;
  result = key.compareTo(data[mid]);
  System.out.println("mid " + mid + " mid value:" + data[mid]);///
  if(result < 0){
  return doSearchRecursively(low , mid - 1 , key);
  }else if(result > 0){
  return doSearchRecursively(mid + 1 , high , key);
  }else if(result == 0){
  return mid;
  }
  }
  return -1;
  }
  public int searchRecursively(T key){
  if(data ==null)return -1;
  return doSearchRecursively(0 , data.length - 1 , key);
  }
  public static void main(String[] args){
  Integer[] data = {1 ,4 ,5 ,8 ,15 ,33 ,48 ,77 ,96};
  BinarySearch binSearch = new BinarySearch(data);
  //System.out.println("Key index:" + binSearch.search(33) );
  System.out.println("Key index:" + binSearch.searchRecursively(3) );
  //String [] dataStr = {"A" ,"C" ,"F" ,"J" ,"L" ,"N" ,"T"};
  //BinarySearch binSearch = new BinarySearch(dataStr);
  //System.out.println("Key index:" + binSearch.search("A") );
  }
  }


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@pclwef.cn

文章转载自:IT专家网

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP