代碼
#include <stdio.h>
#include <stdlib.h>
void PrintHeap(const char* strMsg,int array[],int nLength);
void InsertionSort1(int *items, int count)
void InsertionSort2(int a[],int size);
void PrintArray(const char* strMsg,int array[],int nLength);
int main(int argc, char *argv[])
{
int data[13]={8,5,4,6,13,7,1,9,12,11,3,10,2};
InsertionSort1(data,13);
PrintArray("Insertion Sort:",data,13);
system("PAUSE");
return 0;
}
/*
插入排序思路:
將數組分成兩個地區:已排序地區和未排序地區。首先假設數組的第一個元素處於已排序地區,
第一個元素之後的所有元素都處於未排序地區。
排序時用到兩層迴圈,第一層迴圈用於從未排序地區中取出待排序元素,並逐步縮小未排序地區,
第二層迴圈用於從已排序地區中尋找插入位置(即不斷地從已排序地區中尋找比待排序元素大的元素,
然後將較大的已排序區的元素後移,後移的最終結果是已排序區元素的最後一個元素佔據
待排序元素原來的位置,而已排序區中間空出一個位置),最後將待排序元素插入元素後移後留下的空位。
註:待排序元素所在位置與已排序元素的最後一個元素是相鄰的,因此進行移位迴圈時第一次後移時將已排序元素的最後一個元素直接移至待排序元素的位置即可。元素比較和元素移位共用一個迴圈,即邊比較邊移位。
*/
void InsertionSort1(int *items, int count)
{
int x, y;
int c;
for ( x=1; x<count; ++x )
{
c = items[x];
for ( y=x-1; (y>=0) && (c<items[y]); y-- )
items[y+1] = items[y];
items[y+1] = c;
}
}
void InsertionSort2(int a[],int size)
{
int i,j,v;
//initially,the first item is considered to be sorted
//i divides a into a sorted region,x<i,and unsorted one,x>=i
for(i=1;i<size;i++)
{
//select the item at the beginning of the as yet unsorted section
v=a[i];
//work backwards through the array,finding where v should go
j=i;
//if this element is greater than v,move it up one
while(a[j-1]>v)
{
a[j]=a[j-1];
j--;
if(j<=0) break;
}
//stopped when a[j-1]<=v,put v at position
a[j]=v;
}
}
void PrintArray(const char* strMsg,int array[],int nLength)
{
int i;
printf("%s",strMsg);
for(i=0;i<nLength;i++)
{
printf("%d ",array[i]);
}
printf("\n");
}
參考資料:http://www.ahhf45.com/info/Data_Structures_and_Algorithms/algorithm/commonalg/sort/internal_sorting/insertion_sort/insertion_sort.htm http://baike.baidu.com/view/1193395.htm
http://www.javaeye.com/topic/547734