以前学习排序,从冒泡排序开始,依次接触了插人排序,选择排序,快速排序,合并排序,而这些排序从最简单的开始,都运用了不同的算法方法,比如brute-force,divide-and-conquer,Decrease-and-conquer。以前对插入排序的印象不深,代码也总是记不住,今天从书上看到Decrease-and-conquer,这种思想,重新理解了插入排序在这种方法下的流程。废话少说,给出原书的伪代码以便理解。
Algorithm InsertionSort(A[0...n-1])
//Sorts a given array by insertion sort
//Input:An array A[0...n-1] of n orderable elements
//Output:Array A[0...n-1] sorted in nondecreasing order
for i<-1 to n-1 do
v<-A[i]
j<-i-1
while j>=0 and A[j]>v do
A[j+1]<-A[j]
j<-j-1
A[j+1]<-v
当然我自己也写了源码,以供参考
/*insert sort*/
#include<iostream>
#include<stdlib.h>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void InsertSort(int a[],int n)
{
int v=0,i=0,j=0;
for(i=1;i<=n-1;++i)
{
v=a[i];
j=i-1;
while(j>=0&&a[j]>v)
{
a[j+1]=a[j];
j=j-1;
a[j+1]=v;
}
}
}
int main()
{
const int array_size=5;
int a[5]={5,8,3,2,1};
cout<<"The given array is:";
for(int i=0;i<5;++i)
cout<<a[i]<<' ';
cout<<endl;
InsertSort(a,5);
cout<<"The sorted array is:";
for(int i=0;i<5;++i)
cout<<a[i]<<' ';
cout<<endl;
return 0;
}