1. 程式人生 > >Algs4-1.1.38二分查找與暴力查找

Algs4-1.1.38二分查找與暴力查找

ctx 暴力 void else height dac 一個 d+ tel

1.1.38二分查找與暴力查找。根據1.1.10.4節給出的暴力查找法編寫一個程序BruteForceSearch,在你的計算機上比較它和BinarySearch處理largeW.txt和largeT.txt所需的時間。
解:
暴力查找約用時:2371秒
二分查找約用時: 17秒
技術分享圖片
//暴力查找代碼
import java.util.Date;
public class BruteForceSearch
{
public static int rank(int key,int[] a)
{
for (int i=0;i<a.length;i++)
if (a[i]==key) return i;
return -1;
}//end rank

public static void main(String[] args)
{
int[] whitelist=In.readInts(args[0]);
int postion;
Date timeStart=new Date();
while (!StdIn.isEmpty())
{
int key=StdIn.readInt();
postion=rank(key,whitelist);
}
Date timeEnd=new Date();
StdOut.printf("BruteForceSearch used time:");
StdOut.println(timeEnd.getTime()-timeStart.getTime());
}
}


//二分查找代碼
import java.util.Date;
import java.util.Arrays;
public class BinarySearch
{
public static int rank(int key,int[]a)
{
int lo=0;
int hi=a.length-1;
while (lo<=hi)
{
int mid=lo+(hi-lo)/2;
if (key<a[mid]) hi=mid-1;
else if(key>a[mid]) lo=mid+1;
else return mid;
}
return -1;
}

public static void main(String[] args)
{
int[] whitelist=In.readInts(args[0]);
int postion;
Date timeStart=new Date();
Arrays.sort(whitelist);
while (!StdIn.isEmpty())
{
int key=StdIn.readInt();
postion= rank(key,whitelist);
}
Date timeEnd=new Date();
StdOut.printf("BinarySearch used time:");
StdOut.println(timeEnd.getTime()-timeStart.getTime());
}
}

Algs4-1.1.38二分查找與暴力查找