快速排序算法如下
private  void QuickSort(int[] A,int p,int r){
if(p<r){
int q=Partition(A,p,r);
QuickSort(A,p,q-1);
QuickSort(A,q+1,r); }
}

private  int Partition(int[] A, int p, int r) {
int x=A[r];
int i=p-1;
int temp=0;
for(int j=p;j<=r-1;j++){
if(A[j]<=x){
i++;
temp=A[i];//A[j]跟A[i]交换
A[i]=A[j];
A[j]=temp;
} }
//交换中间的数与末尾的那个参照数
temp=A[i+1];
A[i+1]=A[r];
A[r]=temp;
return i+1;
}
主程序中用
System.out.print("请输入随机数字的数量:");
int number=in.nextInt();
int s[]=new int[number];
for(int i=0;i<number;i++){
s[i]=(int) (Math.random()*number*5);
}
long beforeRunTime=System.currentTimeMillis();
a.QuickSort(s,0,s.length-1);
System.out.println("运行的时间为"+(System.currentTimeMillis()-beforeRunTime));不要说是程序运行过快的结果,我输入10000个数字,不可能快速排序有这么快的,希望指点一下,不知道计算运行时间总为0...

解决方案 »

  1.   

    别用System.currentTimeMillis(),
    用System.nanoTime(),至于是做什么的看注释.long java.lang.System.nanoTime()
    Returns the current value of the most precise available system timer, in nanoseconds. This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow. For example, to measure how long some code takes to execute:    long startTime = System.nanoTime();
       // ... the code being measured ...
       long estimatedTime = System.nanoTime() - startTime;
     
    Returns:The current value of the system timer, in nanoseconds.
    Since:1.5