最近要啃数据结构了哦~~
这一部分简单,直接上代码罗。
Array1.java 代码
- package per;
- public class Array1 {
- public int find(int searchKey, int[] array) {
- int lowBound = 0;
- int uppBound = array.length - 1;
- int curIndex;
- while (true) {
- curIndex = (lowBound + uppBound) / 2;
- if (array[curIndex] == searchKey) {
- return curIndex; //查找到数据,返回下标
- } else if (lowBound > uppBound) {
- break; //未查找到数据
- } else{
- if (array[curIndex] < searchKey) {
- lowBound = curIndex+1; //二分法 处于大的一半
- } else {
- uppBound = curIndex-1; //二分法 处于小的一半
- }
- }
- }
- return -1; //未找到则返回-1
- }
- }
TestArray1.java 代码
- package per;
- import junit.framework.Test;
- import junit.framework.TestCase;
- import junit.framework.TestSuite;
- public class TestArray1 extends TestCase {
- public void testArray1() {
- int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
- assertTrue(array[new Array1().find(9, array)] == 9); //能找到数据
- assertTrue(new Array1().find(0, array) == -1); //不能找到数据
- }
- public static Test suite() {
- return new TestSuite(TestArray1.class);
- }
- public static void main(String args[]) {
- junit.textui.TestRunner.run(suite());
- }
- }
用的 Junit3.8.1,本期节目结束谢谢观看。