【发布时间】:2020-06-13 17:18:16
【问题描述】:
我一直在研究我的数据结构课程的时间复杂度。我的任务是报告 Shell 排序算法并解释其时间复杂度(最佳/最差/平均情况)。我发现这个网站https://stackabuse.com/shell-sort-in-java/ 显示了这个Shell排序算法的时间复杂度:
void shellSort(int array[], int n){
//n = array.length
for (int gap = n/2; gap > 0; gap /= 2){
for (int i = gap; i < n; i += 1) {
int temp = array[i];
int j;
for (j = i; j >= gap && array[j - gap] > temp; j -= gap){
array[j] = array[j - gap];
}
array[j] = temp;
}
}
}
是 O(n log n)。但问题是我仍然对将 logn 设为 logn 或 nlogn 的含义感到困惑。
我也尝试过计步方法,但又一次,我不知道从哪里开始,所以我只是从上面的网站复制并做了这个。
void shellSort(int array[], int n){
//n = array.length
for (int gap = n/2; gap > 0; gap /= 2){ //step 1 = runs logn times
for (int i = gap; i < n; i += 1) { //step 2 = runs n-gap times
int temp = array[i]; //step 3 = 1
int j; //step 4 = 1
for (j = i; j >= gap && array[j - gap] > temp; j -= gap){ //step 5 = i/gap times
array[j] = array[j - gap]; //step 6 = 1
}
array[j] = temp; //step 7 = 1
}
}
}
但我不知道这是否正确,我只是根据这个网站。 https://stackabuse.com/shell-sort-in-java/.
我还尝试比较了插入排序和壳排序之间的总移动次数,因为壳排序是插入排序和冒泡排序的概括。我会附上下面的图片。我还使用了一个在线数字生成器,它将给我 100 个随机数,将其复制并应用于插入排序和 Shell 排序,并将其分配为要排序的数组。
结果就是这样,
插入排序的总移动次数 = 4731
Shell Sort 的总移动次数 = 1954
Shell Sort implementation that tells me the total number of moves it does
Insertion Sort implementation that tells me the total number of moves it does
我从所有这些中了解到的是,尽管 Shell 排序是插入排序的泛化,但在对大型数组(例如 100 个元素)进行排序时,Shell 排序比插入排序快 2 倍。
但最终的问题是,有没有像这种 Shell Sort 算法一样计算时间复杂度的初学者方法?
【问题讨论】:
-
您使用的站点中所述的时间复杂度不正确。 Wikipedia 指出,使用代码中显示的间隙序列进行 shell 排序的最坏情况复杂度为 O(n^2)。网站上显示的公式正确计算出复杂度为 O(n^2),但由于某种原因,文本错误地指出它是 O(n log n)。
标签: java algorithm loops sorting time-complexity