测量三种分类方法的经过时间

时间:2019-04-01 15:49:32

标签: java sorting bubble-sort insertion-sort selection-sort

使用双向链接列表实施三种排序方法插入,选择气泡排序) >,我的目标是创建一种可以测量经过时间且具有纳秒精度的方法。

关于我的代码,我使用:

long startTime = System.nanoTime();

在每种排序方法的开头,并且:

long time = System.nanoTime() - startTime;
return time;

最后。

但是,当涉及到输出时,看来气泡排序所花费的时间比其他两个要少得多,从理论上讲 是不可能的。例如,对于大小为60的列表,插入排序在77108 (ns)中完成,选择排序在276910 (ns)中完成,而冒泡排序在319 ( ns)

下面是计算冒泡排序经过时间的方法产生结果的主要方法

public static long sortBubbleTime(DoublyNodeList a){
    long startTime = System.nanoTime();
    double temp;
    boolean swapped;

    for(int i = 0; i < a.size() - 1; i++) {
        swapped = false;


        for(int j = 0; j < a.size() - i - 1; j++) {


            if(a.getValue(j) > a.getValue(j+1)) {
                temp = a.getValue(j);
                a.setValue(j, a.getValue(j+1));
                a.setValue(j + 1, temp);
                swapped = true;

            }
        if(swapped == false)

            break;
        }
    }

    long time=System.nanoTime() - startTime;
    return time;

}





public void main(){

    long AverageInsertionTime, AverageSelectionTime, AverageBubbleTime;

    long[] InsertionTime = new long[100];
    long[] SelectionTime = new long[100];
    long[] BubbleTime = new long[100];

    int randomHead = random.nextInt(100);
    int randomTail = random.nextInt(100);

    dlist1.setValue(0, randomHead);
    dlist1.setValue(1, randomTail);

    for(int j = 1; j <= 3; j++){
        int randomMid = random.nextInt(100);
        dlist1.insertAfter(dlist1.first(), randomMid);
    }

    for(int k = 0; k < 20; k++){

        AverageInsertionTime = AverageSelectionTime = AverageBubbleTime = 0;

        if(k > 0) {

            for(int j = 0; j < 5; j++) {
                int randomMid = random.nextInt(100);
                dlist1.insertAfter(dlist1.first(), randomMid);
            }
        }

        for(int i = 0; i < 100; i++) {


            for(int j = 1; j <= 5*(k+1); j++){
                int randomMid = random.nextInt(100);
                dlist1.setValue(j-1, randomMid);
            }

            InsertionTime[i] = InsertionSort.sortInsertionTime(dlist1);
            SelectionTime[i] = SelectionSort.sortSelectionTime(dlist1);
            BubbleTime[i] = BubbleSort.sortBubbleTime(dlist1);
        } 

        for(int i = 0; i < 100; i++) {
            AverageInsertionTime = AverageInsertionTime + InsertionTime[i];
            AverageSelectionTime = AverageSelectionTime + SelectionTime[i];
            AverageBubbleTime = AverageBubbleTime + BubbleTime[i];
        }

       System.out.println("List size: " + 5*(k+1));
       System.out.println("Insertion Sort: " + AverageInsertionTime/100);
       System.out.println("Selection Sort: " + AverageSelectionTime/100);
       System.out.println("Bubble Sort: " + AverageBubbleTime/100);
       System.out.println("");

0 个答案:

没有答案