顺序查找
用Java实现顺序查找,代码如下:
/**
* Sequence Search: 顺序查找
* @param src 从哪个数组里找
* @param low 开始查找的数组下标
* @param high 结束查找的数组下标
* @param target 待查找的数
* @return 待查数在数组里的位置,若找不到返回-1
*/
public static int SSearch(int[] src, int low, int high, int target ){
if(low>high){
throw new RuntimeException("low great than high!");
}
//指针指向当前的数组下标
int _p = low;
while(_p<=high){
if(src[_p] == target ){
return _p;
}
_p++;
}
//在数组里没找到待查的数
return -1;
}
二分查找
用Java实现二分查找,代码如下:
/**
* Binary Search: 二分查找
* @param src 已排好序的数组
* @param low 开始查找的数组下标
* @param high 结束查找的数组下标
* @param target 待查找的数
* @return 待查数在数组里的位置,若找不到返回-1
*/
public static int BSearch(int array[], int low, int high, int target ){
//区间的中间位置
int mid ;
while(low<=high){
mid = (low+high)/2;
//待查数在左半区间
if(array[mid]>target){
high = mid - 1;
//待查数在右半区间
}else if(array[mid]<target){
low = mid + 1;
}else{
return mid;
}
}
return -1;
}
测试
以上查找算法的测试代码如下:
public static void main(String[] args) throws FileNotFoundException {
final String path = "C:\\search";
//待查找数据
final String tinyW = "tinyW.txt";
//数组src中的数据文件
final String largeW_bubble = "largeW_bubble.txt";
Scanner sc = new Scanner(new File(path,largeW_bubble));
List<Integer> list = new ArrayList<Integer>();
//-----------------------
int count = 0;
while(sc.hasNextInt()){
list.add(sc.nextInt());
count++;
}
int [] src = new int[count];
count = 0;
//将读到的数据转存到src数组中
for(int i : list){
src[count++] = i;
}
//-----------------------
sc = new Scanner(new File(path,tinyW));
list = new ArrayList<Integer>();
count = 0;
while(sc.hasNextInt()){
list.add(sc.nextInt());
count++;
}
int [] targets = new int[count];
count = 0;
//将读到的数据转存到targets数组中
for(int i : list){
targets[count++] = i;
}
//开始时间
long startTime = System.currentTimeMillis();
//顺序查找
System.err.println("tinyW.txt里的数不在largeW_bubble.txt的里的有: ");
for(int num : targets){
//测试顺序查找
//int position = SSearch(src,0,src.length-1,num);
//测试二分查找
int position = BSearch(src,0,src.length-1,num);
if(position<0){
System.err.print(num+"\t");
}
}
//结束时间
long endTime = System.currentTimeMillis();
System.err.printf("\n二分查找结束,共耗时:%d毫秒", endTime-startTime);
sc.close();
}
顺序查找:
二分查找:
总结
顺序查找
时间复杂度为: O(N) = N
二分查找
时间复杂度为:
O
(N) = log
2
N