数据结构之二分法

最近要啃数据结构了哦~~

这一部分简单,直接上代码罗。

Array1.java 代码
  1. package per;   
  2.   
  3. public class Array1 {   
  4.     public int find(int searchKey, int[] array) {   
  5.         int lowBound = 0;   
  6.         int uppBound = array.length - 1;   
  7.   
  8.         int curIndex;   
  9.         while (true) {   
  10.             curIndex = (lowBound + uppBound) / 2;   
  11.             if (array[curIndex] == searchKey) {   
  12.                 return curIndex;                        //查找到数据,返回下标
  13.             } else if (lowBound > uppBound) {   
  14.                 break;                                  //未查找到数据   
  15.             } else{   
  16.                 if (array[curIndex] < searchKey) {   
  17.                     lowBound = curIndex+1;              //二分法 处于大的一半   
  18.                 } else {   
  19.                     uppBound = curIndex-1;              //二分法 处于小的一半   
  20.                 }   
  21.             }   
  22.         }   
  23.         return -1;                                      //未找到则返回-1
  24.     }   
  25.   
  26. }  

 

TestArray1.java 代码
  1. package per;   
  2.   
  3. import junit.framework.Test;   
  4. import junit.framework.TestCase;   
  5. import junit.framework.TestSuite;   
  6.   
  7. public class TestArray1 extends TestCase {   
  8.     public void testArray1() {   
  9.         int[] array = { 12345678910 };   
  10.         assertTrue(array[new Array1().find(9, array)] == 9);   //能找到数据
  11.         assertTrue(new Array1().find(0, array) == -1);         //不能找到数据
  12.     }   
  13.   
  14.     public static Test suite() {   
  15.         return new TestSuite(TestArray1.class);   
  16.     }   
  17.   
  18.     public static void main(String args[]) {   
  19.         junit.textui.TestRunner.run(suite());   
  20.     }   
  21. }  

 

用的 Junit3.8.1,本期节目结束谢谢观看。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值