直接插入排序实现如下:
- //1、直接插入排序
-
#include
using namespace std;
#define MAXSIZE 20
-
void InsertSort(int r[],int n)
-
{
-
int i,j;
-
for(i=2;i<=n;i++)
-
{
-
if(r[i]<r[i-1])
-
{
-
r[0]=r[i];
-
r[i]=r[i-1];
-
for(j=i-2;r[0]<r[j];--j)
-
r[j+1]=r[j];
-
r[j+1]=r[0];
-
}
-
}
- }
-
int main()
-
{
-
int i,n;
-
int r[MAXSIZE];
-
cout<<"please input the total count you want to sort:"<<endl;
-
cin>>n;
-
cout<<"please input the numbers:"<<endl;
-
for(i=1;i<=n;i++)
-
{
-
cin>>r[i];
-
}
-
-
InsertSort(r,n);
-
for(i=1;i<=n;i++)
-
cout<<r[i]<<" ";
-
return 0;
-
- }
- //希尔排序
-
#include<iostream>
-
using namespace std;
-
-
#define MAXSIZE 20
-
#define MAXNUM 5
-
-
-
void ShellInsert(int r[],int dk,int n)
-
{
-
int i,j;
-
for(i=dk+1;i<=n;i++)
-
{
-
if(r[i]<r[i-dk])
-
{
-
r[0]=r[i];
-
for(j=i-dk;j>0&&r[0]<r[j];j-=dk)
-
r[j+dk]=r[j];
-
r[j+dk]=r[0];
-
}
-
}
-
}
-
-
void ShellSort(int r[],int dlta[],int t,int n)
-
{
-
int k;
-
for(k=0;k<t;k++)
-
ShellInsert(r,dlta[k],n);
-
}
-
-
-
int main()
-
{
-
int i,n,m;
-
int r[MAXSIZE],dlta[MAXNUM];
-
cout<<"please input the total count you want to sort:"<<endl;
-
cin>>n;
-
cout<<"please input the numbers:"<<endl;
-
for(i=1;i<=n;i++)
-
{
-
cin>>r[i];
-
}
-
-
cout<<"please input the Dk numbers:"<<endl; // 增量数目 3
-
cin>>m;
-
cout<<"please input the kd values:"<<endl; //增量值 5,3,1
-
for(i=0;i<m;i++)
-
cin>>dlta[i];
-
ShellSort(r,dlta,m,n);
-
for(i=1;i<=n;i++)
-
cout<<r[i]<<" ";
-
return 0;
-
- }