我在书上看到的说明是:一般情况下选择排序慢于插入排序慢于希尔排序,可是我自己用Python测试了下,竟然是选择排序是最快的,希尔排序比插入排序稍微快一点。。
我自己分析原因可能是插入排序和希尔排序有太多交换元素的操作了,所以效率低,但书上说的是希尔排序会是最快的,请各位大神指点?
我的测试代码在这里:http://paste.ubuntu.com/8385144
PHP中文网2017-04-17 13:33:25
The speed is based on the conditions of time complexity, space complexity, etc. You cannot just write a program to see who is faster. There will be accidents. Please consider the performance factors of the algorithm
高洛峰2017-04-17 13:33:25
Theoretically speaking, selection sort <insertion sort <Hill sort, but the actual time-consuming depends on the sample and specific implementation.
高洛峰2017-04-17 13:33:25
The if statement of insertion sort should be written in the inner loop condition. The time complexity of your insertion sort is the same as the time complexity of selection sort, so it is slow
Java
/**
* Insertion sort based on exchange
* @param array, Array of Comparable to be Sorted
*/
public static void sort( Comparable[] array ){
for (int i = 1; i < array.length; i++) {
for(int j=i;j>0&&less(array[j],array[j-1]);j--){
exch(array, j, j-1);
}
}
}