java版 2分查找

来源:互联网 发布:软件开发行业税率 编辑:程序博客网 时间:2024/05/02 04:58

 
/**
 * 采用2分法实现有序数组的增删查
 * 由于数组定义了大小就不能再改了 所以我们重新定义了size()方法;
 * 将数据组成了一个对象
 * @author leader
 * 2009-11-3
 */
class Array
{
 public static int maxsize ;//数组的长度的最大值
 public static int realsize;
 int [] array ;//数组
 public Array (int maxsize)
 {
  //初始化这个类
  this.maxsize  = maxsize;
  this.array = new int [this.maxsize];
  this.realsize = 0 ;
 }
 /**
  * 给数组添加数据
  */
 public void insert (int ins)
 {
  //当数组还有空间的时候才能往里面插入数据
  int len = this.realsize;
  if(len == maxsize)
  {
   System.out.println("数组已满");
  }
  //由于是有序数组 所以要给新添加进来的数字放到排序后的位置
  int i = 0;
  for ( ;i<this.realsize;i++)
  {
   if(array[i]>ins)
   {
    //插入的数字小于数组中的某个成员的时候 就可以放在这个数字的前面 应为他是有序的排列的
    break;
   }
   
  }
  //讲这个数据以后的数据向后一位 从最后开始移
  for (int j =this.realsize  ;j>i;j--)
  {
   array[j] = array[j-1];
  }
  array[i]=ins;//将插入的数字放在正确的位置
  this.realsize ++;//将数组长度加一
 }
 /**
  * 数组的大小只是给人看的
  * @return
  */
 public int size ()
 {
  return this.realsize;
 }
 public void display ()
 {
  for (int i = 0 ;i<this.realsize;i++)
  {
   System.out.println(array[i]);
  }
 }
 public void delete (int del)
 {
  int i = 0;
  for ( ;i<this.realsize;i++)
  {
   if(array[i]==del)
   {  
    break;
   }
   
  }
  for(int j = i;j<this.realsize;j++)
  {
   array[j]=array[j+1];
  }
  this.realsize--;
 }
 /**
 用二分法找数字
 **/
 public void find (int find)
 {
  int begin = 0;
  int end   = this.realsize;
  
  while (true)
  {
   int tem   = (begin+end)/2;
   if(array[tem]<find)
   {
    begin = tem + 1;

   }else if(array[tem]>find)
   {
    end = tem - 1;
   }
   else {
    System.out.println("find it @ "+tem);
    break;
   }
  }
  

  
 }
}
public class Chape {
 public static void main(String[] args) {
  Array array = new Array(100);
  array.insert(1);
  array.insert(9);
  array.insert(3);
  array.insert(5);
  array.insert(0);
 
  array.delete(1);
  array.display();
  System.out.println("数组长度"+array.size());

  array.find(9);

 }

}