📖
Data Structure
  • 基本概念
  • 线性表
    • 顺序表
    • 链表
    • 广义表
  • 栈
  • 队列
  • 字符串
  • 树
    • 二叉树
    • 二叉搜索树
    • 平衡二叉树
    • 堆
    • 哈夫曼树
  • 图
    • DFS
    • BFS
  • 排序
    • 选择排序
    • 插入排序
    • 比较选择排序和插入排序
    • 希尔排序
  • 常用算法
    • 排序
    • 二叉树遍历
    • 根据两种遍历顺序重构树
    • 二叉树深度
    • 最近公共祖先
    • 回溯集合
    • N Sum
    • union-find
  • 常用算法时间复杂度速查表
由 GitBook 提供支持
在本页

这有帮助吗?

  1. 排序

比较选择排序和插入排序

import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.Stopwatch;

/**
 * @author LFool
 * @create 2020-07-24 18:13
 */
@SuppressWarnings({"rawtypes"})
public class SortCompare {

    public static double time(String alg, Comparable[] arr) {
        Stopwatch timer = new Stopwatch();
        String[] sortType = {"Insertion", "Selection"};
        if (sortType[0].equals(alg)) {
            Insertion.sort(arr);
        }
        if (sortType[1].equals(alg)) {
            Selection.sort(arr);
        }
        return timer.elapsedTime();
    }

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

    public static void main(String[] args) {
        String alg1 = "Insertion";
        String alg2 = "Selection";
        int n = 1000;
        int t = 100;
        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);
    }

    /**
     * Result:
     * For 1000 random Doubles
     *    Insertion is 1.1 times faster than Selection
     */

}
上一页插入排序下一页希尔排序

最后更新于4年前

这有帮助吗?