`
sunwinner
  • 浏览: 204599 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Comparing two sorting algorithms

阅读更多

Generally we compare algorithms by

■ Implementing and debugging them

■ Analyzing their basic properties

■ Formulating a hypothesis about comparative performance

■ Running experiments to validate the hypothesis

 

These steps are nothing more than the time-honored scientific method, applied to the study of algorithms.

 

Suppose you have implemented several sorting algorithms, to validate this hypothesis, we use SortCompare to perform the experiments. We use Stopwatch to compute the running time. The implementation of time() shown here does the job for the basic sorts in this chapter. The “randomly ordered” input model is embedded in the timeRandomInput() method in SortCompare, which generates random Double values, sorts them, and returns the total measured time of the sort for the given number of trials. Using random Double values between 0.0 and 1.0 is much simpler than the alternative of using a library function such as StdRandom.shuffle() and is effective because equal key values are very unlikely. The number of trials is taken as an argument both to take advantage of the law of large numbers (the more trials, the total running time divided by the number of trials is a more accurate estimate of the true average running time) and to help damp out system effects. 

public class Stopwatch { 

    private final long start;

   /**
     * Create a stopwatch object.
     */
    public Stopwatch() {
        start = System.currentTimeMillis();
    } 


   /**
     * Return elapsed time (in seconds) since this object was created.
     */
    public double elapsedTime() {
        long now = System.currentTimeMillis();
        return (now - start) / 1000.0;
    }

} 

 

/**
 * Replace this line with class description.
 * <p/>
 * User: George Sun
 * Date: 9/15/13
 * Time: 9:45 PM
 */
public class SortCompare {

    public static void main(String[] args) {
        String alg1 = args[0];
        String alg2 = args[1];
        int N = Integer.parseInt(args[2]);
        int T = Integer.parseInt(args[3]);

        double t1 = timeRandomInput(alg1, N, T);
        double t2 = timeRandomInput(alg2, N, T);
        StdOut.printf("For %d random Doubles\n      %s is: ", N, alg1);
        StdOut.printf(" %1f times faster than %s\n", t2 / t1, alg2);
    }

    public static double timeRandomInput(String alg, int N, int T) {
        double total = 0.0;
        Double[] a = new Double[N];
        for (int t = 0; t < T; t++) {
            for (int i = 0; i < N; i++) {
                a[i] = StdRandom.uniform();
            }
            total += time(alg, a);
        }
        return total;
    }

    public static double time(String alg, Comparable[] a) {
        Stopwatch timer = new Stopwatch();
        switch (alg) {
            case "Insertion":
                Insertion.sort(a);
                break;
            case "Selection":
                Selection.sort(a);
                break;
            case "Shell":
                Shell.sort(a);
                break;
            case "Merge":
                Merge.sort(a);
                break;
            case "Quick":
                Quick.sort(a);
                break;
            case "Heap":
                Heap.sort(a);
                break;
            case "InsertionSentinel":
                InsertionWithSentinel.sort(a);
                break;
            default:
                System.err.println("No algorithm specified, end.");
                break;
        }

        return timer.elapsedTime();
    }
}

 

分享到:
评论

相关推荐

    Algorithms in C++, Parts 1-4: Fundamentals, Data Structures, Sorting, Searching

    It helps in comparing the efficiency of different algorithms by analyzing how their running times scale with input size. 4. **Big-Oh Notation**: Big-Oh notation is a mathematical notation used to ...

    C++标准库(第二版)英文版.pdf

    The C++ Standard Library A Tutorial and Reference (2nd Edition)+cppstdlib-code.zip C++标准库(第二版)英文版.pdf 非扫描版+源代码 Prefaceto the SecondEdition xxiii Acknowledgments for the Second...

    Lerner -- Python Workout. 50 Essential Exercises -- 2020.pdf

    The exercises cover various aspects of the Python programming language, including basic syntax, data structures, algorithms, and working with external formats such as CSV and JSON. #### Detailed ...

    python programming

    1 Computers and Programs 1 1.1 The Universal Machine . . . . . . . . ....1.2 Program Power .... ....1.4 Hardware Basics ....1.5 Programming Languages ....1.6 The Magic of Python ....1.7 Inside a Python Program ....

    BobBuilder_app

    I also tried an assorted number of sorting routines like double pivot quick sort, timsort, insertion sort and found that they all were slower than the internal .net quicksort routine in my tests. ...

    Effective C#

    - **Value Equality:** Comparing the values of two objects. - **Reference Equality:** Checking if two references point to the same object. - **Custom Equality:** Implementing `IEquatable&lt;T&gt;` to ...

Global site tag (gtag.js) - Google Analytics