前言
插入排序(insertion sort)的基本思想:每次將一個待排序的記錄,按其關鍵字大小插入到前面已經排序好的序列中,直到全部記錄插入完成為止.
直接插入排序
基本思想
假設待排序的記錄存放在數組R[1..n]中。初始時,R[1]自成1個有序區,無序區為R[2..n].從i = 2起直到i = n 為止,依次將R[i]插入當前的有序區R[1..i - 1]中,生成含n個記錄的有序區.
排序方法
將待插入記錄R[i]的關鍵字從右向左依次與有序區中記錄R[j](j=i - 1, i - 2, ....,1)的關鍵字比較:
- 若R[j]的關鍵字大於R[i]的關鍵字,則將R[j]后移一個位置
- 若R[j]的關鍵字小於或等於R[i]的關鍵字,則查找過程結束,j + 1即為R[i]插入位置
c語言實現代碼
InsertSort.c
#include<stdio.h> typedef int ElementType; ElementType arr[10]={2,87,39,49,34,62,53,6,44,98}; ElementType arr1[11]={0,2,87,39,49,34,62,53,6,44,98}; //不使用哨兵,每一次循環需要比較兩次 void InsertSort(ElementType A[],int N) { int i,j; ElementType temp; for(i=1;i<N;i++) { temp=A[i]; for(j=i;j>0;j--) { if(A[j-1]>temp) A[j]=A[j-1]; else break; } A[j]=temp; } } /* 使用A[0]作為哨兵,哨兵有兩個作用: 1 暫時存放待插入的元素 2 防止數組下標越界,將j>0與A[j]>temp結合成只有一次比較A[j]>A[0], 這樣for循環只做了一次比較,提高了效率,無哨兵的情況需要比較兩次,for循環有兩個判斷條件 */ void WithSentrySort(ElementType A[],int N) { int i,j; for(i=2;i<N;i++) { A[0]=A[i]; for(j=i-1;A[j]>A[0];j--) { A[j+1]=A[j]; } A[j+1]=A[0]; } } void Print(ElementType A[],int N) { int i; for(i=0;i<N;i++) { printf(" %d ",A[i]); } } int main() { Print(arr,10); printf("\n"); InsertSort(arr,10); Print(arr,10); printf("\n"); WithSentrySort(arr1,11); Print(arr1,11); printf("\n"); return 0; }
運行結果如下: