插入排序就是將要排序的記錄插入到已經排序號了的記錄系列中去的過程. 插入排序是一種穩定的排序方法,時間複雜度為O(n2).
常見的插入排序演算法有 直接插入排序,折半插入排序,二路插入排序,表插入排序等.
直接插入排序,折半插入排序,,表插入排序 測試通過代碼如下:
// 插入排序.cpp : 定義控制台應用程式的進入點。#include "stdafx.h"#include <iostream>using namespace std;void printArray(int * a,int n){ for(int i=0;i<n;i++) { cout<<a[i]<<" "; } cout<<endl;}//直接插入排序void InsertSort(int * a,int n){for(int i=1;i<n;i++){int value=a[i];int j=i-1;for(;j>=0 && value<a[j];j--){a[j+1]=a[j];//後移}a[j+1]=value;}}//折半插入排序void BInsertSort(int * a,int n){ for(int i=1;i<n;i++) { int low=0,high=i-1;//尋找插入位置while(low<=high){int mid=low+(high-low)/2; //low=(high+low)/2 if(a[i]<a[mid])high=mid-1;elselow=low+1;}//插入位置在low處,及high+1處//後移操作int temp=a[i];for(int j=i-1;j>=low;j--){a[j+1]=a[j];}a[low]=temp; }}const int size=20;//表插入排序typedef int key;typedef struct Node { key value;//記錄關鍵字 int next;//記錄比它大的記錄所在位置}Node;typedef struct {Node r[size];//記錄表int length;//記錄表長度int minIndex;//記錄最小的記錄所在小標}SLinkListType;//求得一個有序鏈表void SLLInsertSort(SLinkListType &SL){ if(SL.length<1) return; SL.r[0].next=-1;//-1表示沒有後續 SL.minIndex=0; for(int i=1;i<SL.length;i++) { if(SL.r[i].value<SL.r[SL.minIndex].value) { SL.r[i].next=SL.minIndex; SL.minIndex=i; } else { int pre=SL.minIndex; int p=SL.r[SL.minIndex].next; while(p!=-1 && SL.r[i].value>=SL.r[p].value) { pre=p; p=SL.r[p].next; } //第i個記錄插入在pre和p之間 SL.r[pre].next=i; SL.r[i].next=p; } }}//輸出表插入排序得到的結果void printInsResult(SLinkListType SL){ int p=SL.minIndex; while (p!=-1) { cout<<SL.r[p].value<<" "; p=SL.r[p].next; }}int _tmain(int argc, _TCHAR* argv[]){int a[]={49,38,65,97,76,13,27,49}; int n=sizeof(a)/sizeof(int);printArray(a,n);//直接插入排序 //InsertSort(a,n);//折半插入排序//BInsertSort(a,n);//表插入排序SLinkListType SL;for(int i=0;i<n;i++){ SL.r[i].value=a[i];} SL.length=n;SLLInsertSort(SL); printInsResult(SL);//printArray(a,n);system("PAUSE");return 0;}
參考書籍:資料結構(C語言版 嚴蔚敏) 插入排序章節