有n个元素,其中前m个已经有序,后n-m个是无序状态,使用选择排序毫无意义,于是使用一种新的方法插入排序。
设有一个数组List如下:
List={10,18,25,30,23,17,45,35};
List[4]应该插入List[1]和List[2]之间,先把List[4]->temp,List[2]和List[3]后移,再temp->List[2]。
我们在排序过程中,把整个数组分为两个部分,前面有序的一部分和后面无序的一部分,把无序的部分插入有序的部分。
对于任意的一个无序表,我们把无序表第一个数的index设为1即,firstOutOfOrderIndex=1;通过第一次插入,由元素0和1组成了一个有序表,2~n成了一个无序表,进行插入排序。
void insertSort()
{
for(firstOutOfOrder=1;firstOutOfOrder<length;firstOutOfOrder++)
if(List[firstOutOfOrder]<item[firstOutOfOrder-1])
{
temp=List[firstOutOfOrder];
insertIndex=firstOutOfOrder;
do
{
List[insertIndex]=List[insertIndex-1];
insertIndex--;
}
while(List[insertIndex-1]>temp&&insertIndex>0)
List[insertIndex]=temp;
}
}
以下是基于数组的插入排序具体实现
#include <iostream>
using namespace std;
int main()
{
int List[10]={22,3,45,1,87,99,42,42,54,67};
for(int firstOutOfOrderIndex=1;firstOutOfOrderIndex<10;firstOutOfOrderIndex++)
{
if(List[firstOutOfOrderIndex]<List[firstOutOfOrderIndex-1])
{
int temp=List[firstOutOfOrderIndex];
int insertIndex=firstOutOfOrderIndex;
do
{
List[insertIndex]=List[insertIndex-1];
insertIndex--;
}
while(List[insertIndex-1]>temp&&insertIndex>0);
List[insertIndex]=temp;
}
}
for(int i=0;i<10;i++)
cout<<List[i]<<endl;
return 0;
}