代碼是何其的相似啊!!/*
Name: InsertSort
Copyright:
Author: huowolf
Date: 05/07/15 16:18
Description: 直接插入排序的實現
*/
#include <iostream>
using namespace std;
int arr[]={-1,48,62,35,77,55,14,35,98};
void InsertSort(int a[],int length);
void Output(int a[],int length);
int main()
{
InsertSort(arr,8);
Output(arr,8);
return 0;
}
void InsertSort(int a[],int length)
{
int i,j;
for(i=2;i<=length;i++)
{
if(a[i]<a[i-1])
{
a[0] = a[i]; //拷貝爲哨兵
for(j=i-1;a[0]<a[j];j--)
a[j+1]=a[j]; //記錄後移,尋找插入位置
a[j+1] = a[0]; //插入
}
}
}
void Output(int a[],int length)
{
for(int i=1;i<=length;i++)
cout<<a[i]<<" ";
}
/*
Name: ShellSort
Copyright:
Author: huowolf
Date: 05/07/15 16:18
Description: 希爾排序的實現
*/
#include <iostream>
using namespace std;
int arr[]={-1,48,62,35,77,55,14,35,98};
void ShellSort(int a[],int length);
void Output(int a[],int length);
int main()
{
ShellSort(arr,8);
Output(arr,8);
return 0;
}
void ShellSort(int a[],int length)
{
int i,j;
int d = length; //將增量初始化爲表長
do{
d = d/3+1; //增量序列 (一種比較經典的增量取法,但並沒有給出最優性證明)
for(i=d+1;i<=length;i++)
{
if(a[i]<a[i-d]) //在同一子序列中相鄰的前後元素
{
a[0] = a[i];
for(j=i-d;j>0 && a[0]<a[j];j-=d) //記錄後移,尋找插入位置
a[j+d] = a[j];
a[j+d] = a[0];
}
}
}while(d>1);//增量爲1,停止循環
}
void Output(int a[],int length)
{
for(int i=1;i<=length;i++)
cout<<a[i]<<" ";
}