插入排序的基本方法是:每一步将一个待排序的元素,按照其排序码(数值大小)大小,插入到已经排好序的一组元素中,直到全部插入为止。
(一)InsertSort直接插入排序:O(n^2) 稳定
基本思路:每一个待排序的数,依次从后向前和之前排好的进行比较,最后放在小于或等于他的元素后面。
void InsertSort(int array[]){
for(int i=1;i<array.Length;i++) //这里面是数组下标,array[0]是默认第一个排好的项
{
int j=i-1;
int temp=array[i];
while((j>=0)&&(array[j]>temp))//与已排好的逐一进行比较,如果temp大则向后移
{
array[j+1]=array[j];
j--;
}
array[j+1]=temp;
}
}
(二)BinaryInsertSort折半插入排序 :O(n^2) 稳定
基本思路:还是直接插入排序的思想,只不过对已排好序的元素进行折半,将middle值与待排序元素进行比较。
void BinaryInsertSort(int array[]){
int low,high,middle;
for(int i=1;i<array.Length;i++){
temp=array[i];
low=0;high=i-1;
while(low<high){
middle=(low+high)/2;
if(array[middle]>temp)
high=middle-1;
else
low=middle+1; //<=时的情况是一样的,low会跑到middle的后面
}
for(int j=i-1;j>=low;j--)
array[j+1]=array[j];
array[low]=temp;
}
}
(三)希尔排序:O(n^1.25) 不稳定
基本思路:重点是添加了一个步长变量:gap,用来将数组分成几组(具体分成几组不重要),然后两两进行比较,交换位置(实质上希尔排序是一个交换类型的排序)。
gap的初始值定为2/n,gap/=2依次减少。
void ShellSort(int array[],int n){ //n为数组元素个数
for(int gap=2/n;gap>0;gap/=2){
for(int i=gap;i<n;i++)
for(int j=i=gap;j>0 && array[j]>array[j+gap];j-=gap)
Swap(array[j],array[j+gap];
}
void Swap(int i,int j){
int temp;
temp = i;
i=j;
i=temp;
}