递归插入排序运行时间是否比迭代更快?

时间:2018-02-03 21:20:15

标签: java recursion insertion-sort

我正在使用迭代和递归函数测试插入排序的运行时间。

但是,我的结果显示迭代版本的排序时间比递归版本要长。这是对的吗?

    // Used to determine how long a sort took
    private long startTime, stopTime;
    public int[] recursiveSort(int[] list){
        // Start the clock
        this.startTime = System.nanoTime();
        int n = list.length;
        insertionSortRecursive(list, n);
        // Stop the clock
        this.stopTime = System.nanoTime();
        return list;
    }

    public void insertionSortRecursive(int[] arr, int n){
        // Base case
        if (n <= 1)
            return;

        // Sort first n-1 elements
        insertionSortRecursive( arr, n - 1 );

        // Insert last element at its correct position in sorted array.
        int last = arr[n - 1];
        int j = n - 2;

        // Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position.
        while (j >= 0 && arr[j] > last){
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = last;
    }

我的迭代版本如下。我已经运行了一个大小为3000的随机数组的测试50,对于所有这些,递归地对数组进行排序所花费的时间比迭代时间要少。

public int[] iterativeSort(int[] list){
    // Start the clock
    this.startTime = System.nanoTime();

    int n = list.length;

    for (int i = 1; i < n; ++i){
        int key = list[i];
        int j = i-1;

        /* Move elements of list[0..i-1], that are greater than key, to one position ahead of their current position */
        while (j >= 0 && list[j] > key){
            list[j + 1] = list[j];
            j = j - 1;

        }
        list[j + 1] = key;
    }

    // Stop the clock
    this.stopTime = System.nanoTime();
    return list;
}

0 个答案:

没有答案