首先,這裏(用Java)我Shell排序代碼:Shell排序的時間複雜度?
public char[] shellSort(char[] chars) {
int n = chars.length;
int increment = n/2;
while(increment > 0) {
int last = increment;
while(last < n) {
int current = last - increment;
while(current >= 0) {
if(chars[current] > chars[current + increment]) {
//swap
char tmp = chars[current];
chars[current] = chars[current + increment];
chars[current + increment] = tmp;
current -= increment;
}
else { break; }
}
last++;
}
increment /= 2;
}
return chars;
}
這是一個正確實施殼牌的排序(忘記了現在大概最有效的差距序列 - 例如,1,3,7,21。 ..)?我問,因爲我聽說Shell Sort的最佳時間複雜度是O(n)。 (見http://en.wikipedia.org/wiki/Sorting_algorithm)。我無法看到我的代碼實現了這種效率水平。如果我給它增加了啓發式,那麼是的,但是按現在的樣子,沒有。
這就是說,我現在的主要問題 - 我難以計算我的Shell排序實現的大O時間複雜度。我確定最外層循環爲O(log n),中間循環爲O(n),最內層循環也爲O(n),但我意識到內部兩個循環實際上不會是O n) - 他們會比這少得多 - 他們應該是什麼?因爲很明顯,這個算法比O((log n)n^2)運行得更有效率。
任何指導都非常感謝,因爲我很迷茫! :P
請參閱[shell-sort-java-example](http://stackoverflow.com/questions/4833423/shell-sort-java-example) – nawfal