/**
* 线性查找
*/
@Test
public void OrderSearch() {int[] array = new int[]{-10,-5,0,5,10,15,20};
boolean flag = false;
int target = 20;
for (int i = 0; i < array.length; i++) {if (array[i] == target) {
flag = true;
System.out.println("存在要查找的数字,下标为:" + i);
break;
}
}
if (!flag) {System.out.println("要查找的数字不存在");
}
}
/**
* 二分查找
*/
@Test
public void TwoPointSearch() {int[] array = new int[]{-10, -5, 0, 5, 10, 15, 20};
int target = 20;
boolean flag = false;
int start = 0;
int end = array.length - 1;
while (start <= end) {int middle = (start + end) / 2;
if (array[middle] == target) {
flag = true;
System.out.println("存在要查找的数字,下标为:" + middle);
break;
} else if (target < array[middle]) {end = middle - 1;} else {start = middle + 1;}
}
if (!flag) {System.out.println("要查找的数字不存在");
}
}