Here is the class on gist https://gist.github.com/2605302
我多次用不同档案对其进行测试,即使对双轨搜索的比较较少,所花费的时间是ALWAYS。 什么是错的?
public static int linerSearch ( String array [], String word, long resultsArray [])
{
int comparisons = 0;
int pos = -1;
//i have started the timer where the search actualy starts
long start = System.nanoTime ();
for (int i = 0; i < array.length; i++){
comparisons = comparisons + 1;
if (array [i].equals (word)){
pos = i;
break;
}
}
long stop = System.nanoTime ();
long total = stop - start;
resultsArray [0] = total;
resultsArray [1] = (long) (long) array.length;
resultsArray [2]= (long) (long) comparisons;
return pos;
}
这里是下届双阶等级。
public static int binarySearch (String [] array, String word, resultsArray []) {
int start = 0;
int end = array.length - 1;;
int midPt;
int pos = -1;
int comparisons2 = 0;
long start2 = System.nanoTime ();
Arrays.sort (array);
while (start <= end) {
midPt = (start + end) / 2;
comparisons2 = comparisons2 + 1;
if (array [midPt].equalsIgnoreCase (word)) {
pos = midPt;
break;
}
else if (array [midPt].compareToIgnoreCase (word) < 0) {
start = midPt + 1;
comparisons2 = comparisons2 + 1;
//camparisons2 addition was added inside this elseif and other elseif as a work around for not breaking the elseif statement tree, if it has made it two the last elseif then two camparisons after the first one will have been done
} else if (array [midPt].compareToIgnoreCase (word) > 0) {
comparisons2 = comparisons2 + 2;
end = midPt - 1;
}
}
long stop2 = System.nanoTime ();
long total2 = stop2 - start2;
resultsArray [0] = total2;
resultsArray [1] = (long) (long) array.length;
resultsArray [2]= (long) (long) comparisons2;
return pos;
}
编辑:我还要补充一点,一是在没有这一法典线以前已经分类的阵列上它,而它现在仍然是一个更长的时间。