十大经典排序算法之希尔排序【四】
【希尔排序】(Shell Sort)
a) 原理
希尔排序是1959年由Shell发明,是简单插入排序的改进版。不同之处在于它会优先比较距离较远的元素。又叫缩小增量排序。
b) 演示动态图

c) 算法步骤
l 确定一个缩小增量序列:a1,a2,a3…ak,其中序列逐渐缩小,ak=1;
l 按照每个增量对原始数组进行k次插入排序;
l 每一次排序,即将原始数组分割成若干长度为m的子序列,分别对各子表进行插入排序。
l 最后增量为1时,即将整个序列作为一个表来处理。
d) 代码实现
1 #include <iostream> 2 #include <cmath> 3 using namespace std; 4 void PrintStr(int [],int); 5 void ShellSort(int [],int); 6 7 int main() 8 { 9 int str[] = {2,5,6,1,53,26,64,18,98,18}; 10 int strlen = sizeof(str)/sizeof(str[0]); 11 cout << "排序前数组序列:"; 12 PrintStr(str,strlen); 13 ShellSort(str,strlen); 14 cout << "排序后数组序列:"; 15 PrintStr(str,strlen); 16 return 0; 17 } 18 19 void ShellSort(int str[],int strlen) 20 { 21 for (int gap = floor(strlen/2);gap > 0;gap = floor(gap/2)) 22 { 23 cout << gap << endl; 24 for(int i = gap;i < strlen;i++) 25 { 26 int j = i; 27 int current = str[i]; 28 while(j - gap >=0 && current < str[j - gap]) 29 { 30 str[j] = str[j - gap]; 31 j = j - gap; 32 } 33 str[j] = current; 34 } 35 } 36 } 37 38 void PrintStr(int str[],int strlen) 39 { 40 for (int i = 0;i < strlen;i++) 41 cout << str[i] << ','; 42 cout << endl; 43 }
参考博客:https://www.cnblogs.com/onepixel/articles/7674659.html,再次感谢!

浙公网安备 33010602011771号