Java 堆排序与插入排序JMH基准:为什么我的插入impl。花更少的时间?

Java 堆排序与插入排序JMH基准:为什么我的插入impl。花更少的时间?,java,algorithm,sorting,insertion-sort,heapsort,Java,Algorithm,Sorting,Insertion Sort,Heapsort,我已经实现了插入排序和堆排序。理论上,堆排序的时间复杂度为nlogn,插入的时间复杂度为n^2。为什么,那么我的插入实现对一个100000长的数组进行排序要快大约x6倍 我使用JMH对每个排序算法的平均时间进行基准测试。 以下是我的基准代码: import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import

我已经实现了插入排序和堆排序。理论上,堆排序的时间复杂度为nlogn,插入的时间复杂度为n^2。为什么,那么我的插入实现对一个100000长的数组进行排序要快大约x6倍

我使用JMH对每个排序算法的平均时间进行基准测试。 以下是我的基准代码:

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

public class MyBenchmark {

// setup the benchmark - create a new array for each iteration
    @State(Scope.Thread)
    public static class MyState {
        int[] array = null;

        @Setup(Level.Iteration)
        public void doSetup() {
            array = createArray(100000, 0, 100);
        }
    }

    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void insertionSort(MyState state) {
        int[] array = state.array;

        for (int i = 1; i < array.length; i++) {
            int element = array[i];
            for (int j = i - 1; j >= 0; j--) {
                if (element < array[j]) {
                    int temp = array[j];
                    array[j] = element;
                    array[j + 1] = temp;
                } else {
                    break;
                }
            }
        }
    }

    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.SECONDS)
    public void heapSort(MyState state) {
        int[] array = state.array;
        sort(array, array.length);
    }

    public static void sort(int[] arr, int size) {

        for (int i = 0; i < size;) {
            maxHeapify(size, arr);
            int temp = arr[0];
            arr[0] = arr[size - 1];
            arr[size - 1] = temp;
            size--;
        }
    }

    private static void maxHeapify(int size, int[] arr) {
        int nonLeafs = size / 2;
        for (int i = nonLeafs; i > 0; i--) {
            int arrayPos = heapToArrayPos(i), leftChild = heapToArrayPos(leftChild(i)),
                    rightChild = heapToArrayPos(rightChild(i));
            if (rightChild < size) {
                if (arr[rightChild] < arr[leftChild]) {
                    if (arr[arrayPos] < arr[leftChild]) {
                        switchWithLeftChild(arrayPos, arr);
                    }
                } else if (arr[arrayPos] < arr[rightChild]) {
                    switchWithRightChild(arrayPos, arr);
                }
            } else if (arr[arrayPos] < arr[leftChild]) {
                switchWithLeftChild(arrayPos, arr);
            }
        }
    }

    private static int heapToArrayPos(int heap) {
        return heap - 1;
    }

    private static int rightChild(int pos) {
        return pos * 2 + 1;
    }

    private static int leftChild(int pos) {
        return pos * 2;
    }

    private static void switchWithRightChild(int pos, int[] arr) {
        int father = arr[pos];
        int childPos = heapToArrayPos(rightChild(pos + 1)), child = arr[childPos];
        arr[childPos] = father;
        arr[pos] = child;
    }

    private static void switchWithLeftChild(int pos, int[] arr) {
        int father = arr[pos];
        int childPos = heapToArrayPos(leftChild(pos + 1)), child = arr[childPos];
        arr[childPos] = father;
        arr[pos] = child;
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder().include(MyBenchmark.class.getSimpleName()).forks(1).build();

        new Runner(opt).run();
    }

    public static int[] createArray(int length, int minValue, int maxValue) {
        return IntStream.generate(() -> ThreadLocalRandom.current().nextInt(minValue, maxValue)).limit(length)
                .toArray();
    }

    public static int[] createArray(int length) {
        return createArray(length, 0, 10);
    }

    public static int[] createArray(int minValue, int maxValue) {
        return createArray(10, minValue, maxValue);

    }
}
import java.util.concurrent.ThreadLocalRandom;
导入java.util.concurrent.TimeUnit;
导入java.util.stream.IntStream;
导入org.openjdk.jmh.annotations.Benchmark;
导入org.openjdk.jmh.annotations.BenchmarkMode;
导入org.openjdk.jmh.annotations.Mode;
导入org.openjdk.jmh.annotations.OutputTimeUnit;
导入org.openjdk.jmh.runner.runner;
导入org.openjdk.jmh.runner.RunnerException;
导入org.openjdk.jmh.runner.options.options;
导入org.openjdk.jmh.runner.options.OptionsBuilder;
公共类MyBenchmark{
//设置基准-为每个迭代创建一个新数组
@状态(Scope.Thread)
公共静态类MyState{
int[]数组=null;
@设置(级别.迭代)
公共无效剂量设置(){
array=createArray(100000,01000);
}
}
@基准
@基准模式(模式平均时间)
@输出时间单位(时间单位秒)
公共void insertionSort(MyState状态){
int[]数组=state.array;
for(int i=1;i=0;j--){
if(元素<数组[j]){
int temp=数组[j];
数组[j]=元素;
阵列[j+1]=温度;
}否则{
打破
}
}
}
}
@基准
@基准模式(模式平均时间)
@输出时间单位(时间单位秒)
公共无效堆端口(MyState状态){
int[]数组=state.array;
排序(数组、数组、长度);
}
公共静态无效排序(int[]arr,int size){
对于(int i=0;i0;i--){
int arrayPos=heaptorarraypos(i),leftChild=heaptorarraypos(leftChild(i)),
rightChild=HeaptoraryPos(rightChild(i));
if(rightChild<大小){
if(arr[rightChild]ThreadLocalRandom.current().nextInt(minValue,maxValue)).limit(length)
.toArray();
}
公共静态int[]createArray(int-length){
返回createArray(长度为0,10);
}
公共静态int[]createArray(int minValue,int maxValue){
返回createArray(10,minValue,maxValue);
}
}
以下是基准测试结果:

JMH 1.12(51天前发布) 虚拟机版本:JDK 1.8.0_65,虚拟机25.65-b01 VM调用程序:C:\Program Files\Java\jdk1.8.0\U 65\jre\bin\Java.exe VM选项:-Dfile.encoding=UTF-8-Xbootclasspath:C:\Program Files\Java\jdk1.8.0_65\jre\lib\resources.jar;C:\程序 Files\Java\jdk1.8.0_65\jre\lib\rt.jar;C:\程序 Files\Java\jdk1.8.0_65\jre\lib\jsse.jar;C:\程序 Files\Java\jdk1.8.0_65\jre\lib\jce.jar;C:\程序 Files\Java\jdk1.8.0_65\jre\lib\charsets.jar;C:\程序 Files\Java\jdk1.8.0_65\jre\lib\jfr.jar;C:\程序 Files\Java\jdk1.8.0\u 65\lib\tools.jar
预热:20次迭代,每次1秒
测量:20次迭代,每次1s
超时:每次迭代10分钟
线程:1个线程,将同步迭代
基准模式:平均时间,时间/操作
基准:org.sample.MyBenchmark.heapSort

运行进度:完成0.00%,预计到达时间00:01:20
分叉:1/1
预热迭代1:17.651s/op
预热迭代2:16.004 s/op
预热迭代3:14.640s/op
预热迭代4:14.699秒/次
预热迭代5:14.836s/op
预热迭代6:14.900秒/次
预热迭代7:14.758s/op
预热迭代8:15.084 s/op
预热迭代9:15.652s/op
预热迭代10:15.121秒/次
预热迭代11:15.315 s/op
预热迭代12:15.299s/op
预热迭代13:15.234秒/次
预热迭代14:14.822 s/op
预热迭代15:15.078 s/op
战争
maxHeapify(size, arr);
int count = size;
while (count > 0)
{
    int save = arr[0];      // save the largest item
    arr[0] = arr[count-1];  // move last item to top
    arr[count-1] = save;    // and place the largest item
    count = count - 1;      // reduce the count
    SiftDown(0);            // sift item into place
}