#include <iostream>
using namespace std;
template<class T>
void myswap(T &i,T &j){
T flag=i;
i=j;
j=flag;
}
template<class T>
void ShellSort(T str[],int n){
int gap=n;
int flag; //用来判断是否继续进行交换
while (gap>0)
{
gap/=2; //shell方法
do
{
flag=0;
for (int i=0;i<n-gap;i++)
{
int j=i+gap;
if (str[i]>str[j])
{
myswap(str[i],str[j]);
flag=1; //当flag为1时,说明数据进行过交换,此时顺序改变,还有可能存在可以交换的数据
}
}
}while (flag==1); //当flag为0时,说明已经无法再交换
}
}
int main()
{
int str[]={1,2,4,5,3,6};
ShellSort(str,6);
for (int i=0;i<6;i++)
{
cout<<str[i]<<" ";
}
cout<<endl;
return 0;
}
排序算法之希尔排序
最新推荐文章于 2022-10-29 16:38:24 发布