直接插入排序(稳定)
时间复杂度O(n2)
#include<iostream>
using namespace std;
void insertsort(int a[],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
temp=a[i]; //x定为哨兵
for(j=i-1;j>=0&&temp<a[j];j--) //向前依次寻找插入位置
a[j+1]=a[j];
a[j+1]=temp; //插入
}
}
int main()
{
int i;
int a[6]={52,13,5,6,7,9};
insertsort(a,6);
for(i=0;i<6;i++)
cout<<a[i]<<" ";
}
希尔排序(不稳定)
#include<iostream>
using namespace std;
void shellsort(int a[],int n) //分组跳跃式比较排序
{
int i,j,temp;
for(int d=n/2;d>0;d/=2) //缩小分组的长度
{
for(i=d;i<n;i++) //一次分组间的跳跃式比较排序
{
temp=a[i];
for(j=i-d;j>=0&&a[j]>temp;j-=d)
a[j+d]=a[j];
a[j+d]=temp;
}
}
}
int main()
{
int i,a[]={12,8,3,13,9,23,88,7};
shellsort(a,8);
for(i=0;i<8;i++)
cout<<a[i]<<" ";
return 0;
}
折半插入排序(稳定)
直接插入排序的改进(引入了二分查找)
时间复杂度:最好情况(nlog2n) 最坏情况(O(n2)) 平均情况(O(n2))
#include<iostream>
using namespace std;
void sort(int a[],int n)
{
int i,j;
for(i=1;i<n;i++)
{
int tmp=a[i],low=0,high=i-1,mid;//low到high之间为前面已排好的序列
while(low<=high) //寻找插入位置,即最终low位置之前
{
mid=(low+high)/2;
if(tmp>a[mid])
low=mid+1;
else
high=mid-1;
}
for(j=i-1;j>=low;j--) //待排元素与插入位置之间的元素向后移动一位
a[j+1]=a[j];
a[low]=tmp; //插入
}
}
int main()
{
int i,a[]={2,5,6,3,45,34,35,25};
sort(a,8);
for(i=0;i<8;i++)
cout<<a[i]<<" ";
}