1、希尔排序
下面展示一些 代码
。
// An highlighted block
#include <iostream>
using namespace std;
void display(int a[],int size);
void sort(int a[],int size);
int main()
{
int a[]={10,57,14,24,21,1,2,6,54,12};
int size=sizeof(a)/sizeof(a[0]);
cout<<"排序前:"<<endl;
display(a,size);
cout<<"排序后:"<<endl;
sort(a,size);
system("pause");
return 0;
}
void display(int a[],int size)
{
int i;
for(i=0;i<size;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
void sort(int a[],int size)
{
int i,j,step;
//step步长是根据10个元素这个情况定义的
/*3个for循环
第一个for循环,设置出它的步长
第二个for循环,设置子数组,从0开始,小于步长
第三个for循环,从j+step开始,小于数组长,每次循环条件加步长
*/
for(step=size/2;step>0;step=step/2)
{
for(i=0;i<step;i++)//子数组的编号
{
for(j=step+i;j<size;j=step+j)//数组下标j,数组步长下标step+j
{
int temp=a[j];//把数组下标j的值放到temp中
int k=j-step;
while(k>=0&&temp<a[k])
{
a[k+step]=a[k];//大值往后插入
k=k-step;
}
a[k+step]=temp;//小值往前插
}
}
display(a,size);
}
}