本人是java初学者,在这里请教一下高手问题,我看的书里写了Arrays类里面包含了选择排序和顺序查找,二分查找方法,我现在自己建立了一个类Timing,希望在主文件中进行顺序查找和二分查找的效率比较,可是当我运行程序后,明明经过了有十几秒的时间,可是不论是顺序查找还是二分查找的结果都是0.0秒,所以我觉得很奇怪,不知道有什么问题,我在这里附上我的java程序:
这里是Arryas方法:
import java.util.*;
public class Arrays {
int[] arr = new int[10];
Arrays(){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter 10 numbers: ");
for(int i = 0; i < 10; i++){
arr[i] = sc.nextInt();
}
}
public static void selectionSort(int[] arr){
int smallIndex; //index of minimum value in sublist
int pass,j,n = arr.length;
int temp;
//pass has the range 0 to n-2
for(pass = 0; pass < n-1; pass++)
{
smallIndex = pass;
for(j = pass+1; j < n; j++) {
if( arr[smallIndex] > arr[j] )
smallIndex = j;
}
temp = arr[smallIndex];
arr[smallIndex] = arr[pass];
arr[pass] = temp;
}
}
public void Show(){
for(int i=0 ;i < arr.length; i++)
System.out.print(arr[i]+" ");
}
//顺序查找
public static int seqSearch(int[] arr,int first,int last,int target)
{
for(int i = first; i < last; i++)
if (arr[i] == target)
return i;
return -1;
}
//二叉查找(二分法)
public static int binSearch(int[] arr,int first,int last,int target)
{
int mid;
int midValue;
while(first<last)
{
mid = (first+last)/2;
midValue = arr[mid];
if( target == midValue )
return mid;
else if(target < midValue)
last = mid;
else if(target > midValue)
first = mid+1;
}
return -1;
}
}
下面是Timing类:
import java.util.Date;
public class Timing {
long t;
Date currentDate = new Date();
Timing(){
t = currentDate.getTime();
}
double start(){
t = currentDate.getTime();
return (double)t;
}
double stop(){
return (double)(currentDate.getTime());
}
}
下面是主文件:
import java.util.Random;
import java.text.DecimalFormat;
public class Program4_1 {
public static void main(String[] args){
final int ARRAY_SIZE = 100000, TARGET_SIZE = 50000;
int[] listSeq = new int[ARRAY_SIZE],
listBin = new int[ARRAY_SIZE],
targetList = new int[TARGET_SIZE];
int i;
Timing t = new Timing();
double seqTime,binTime;
Random rnd = new Random();
DecimalFormat fmt = new DecimalFormat("#.000");
//initialize
for(i = 0; i < ARRAY_SIZE; i++)
listSeq[i] = listBin[i] = rnd.nextInt(1000000);
for(i = 0; i < TARGET_SIZE; i++)
targetList[i] = rnd.nextInt(1000000);
//time the sequential search with elements from listSeq
t.start();
for(i = 0; i < TARGET_SIZE; i++)
Arrays.seqSearch(listSeq,0,ARRAY_SIZE,targetList[i]);
seqTime = t.stop()-t.start();
System.out.println("Sequential Search takes "+seqTime+" seconds.");
// sort listBin
Arrays.selectionSort(listBin);
//time the binary search with elements from listBin
t.start();
for(i = 0; i < TARGET_SIZE; i++)
Arrays.binSearch(listBin,0,ARRAY_SIZE,targetList[i]);
binTime = t.stop()-t.start();
System.out.println("Binary Search takes "+binTime+" seconds.");
System.out.println("Ratio of sequential to binary search time is "+fmt.format(seqTime/binTime));
}
}
先谢谢啦!