为什么我的快速表演在O(2 ^ n)表演

时间:2012-12-08 16:09:58

标签: runtime analysis quicksort

我必须通过每次增加100的数组大小来对快速排序执行运行时分析。但是,当我使用System.nanoTime测量运行时时,结果并不像我预期的那样(我的图形看起来更像是O(2 ^ n))。当阵列达到800左右时,时间就会开始。有人可以告诉我我的代码出错了。

此外,计数部分有点无关紧要,因为我只想在每个数组大小上运行一次快速排序。

import java.util.Random;


public class Quickworking {

public static void main(String[] args) {
    Random rand = new Random();
    int count2;
    long total = 0;
    count2 = 1;
    int [] myArray = new int[1400];   

                //generates random array
    for (int i = 0; i < myArray.length; i++){
        myArray[i] = rand.nextInt(100) + 1;
        //System.out.print(myArray[i] + ", ");
    }

            //loop sort n amount of times
    for (int count = 0; count < count2; count++){

            //calls the sort method on myArray giving the arguments
        long start = System.nanoTime();
        sort( myArray, 0, myArray.length - 1 );
        long end = System.nanoTime();
        System.out.println(end - start );
        total += (end - start);
    }
    //long average = (long) total / (long) count2;

    //System.out.println(average);


    //prints the sorted array
    //for (int i = 0; i <myArray.length; i++){
    //  System.out.print(myArray[i] + ", ");
    //}

}

public static int sort(int myArray[], int left, int right){
    int i = left, j = right;
    int temp;
    int pivot = myArray[(left + right) / 2];
    //System.out.println("here are the pivot numbers " + pivot + ", ");


    if (i <= j){

        while (myArray[i] < pivot) //&& (i<right))  
            i++;
        while (myArray[j] > pivot) //&& (j>left))  
            j--;
        if (i <= j){
            temp = myArray[i];
            myArray[i] = myArray[j];
            myArray[j] = temp;
            i++;
            j--;


        }
    } 

    if (left < j) sort(myArray, left, j);
    if (i < right) sort(myArray, i, right);

    return i;

}
}

2 个答案:

答案 0 :(得分:2)

排序已经排序的数组时,Quicksort的行为是O(n ^ 2)。在您的代码中第一次对数组进行排序后,您将对排序的数组进行排序。这将给你最快速排序的情况。你需要每次生成一个全新的随机数组来真正测试它。

答案 1 :(得分:1)

QuickSort在已排序的数据上表现不佳。 看这里: http://en.wikipedia.org/wiki/Quicksort

您应该在for循环中随机化数组,以获得更准确的结果。

相关问题