在阅读此博文前,请先阅读我的博文“C#排序算法——基类设计 “,以了解基类的结构。
在写代码前,我们先来了解一下插入法排序过程:
第1次遍历,构造一个只有一个元素的子集,list[0],显然,这个子集是有序的(因为只有一个元素啊)。
第2次遍历,将list[1]插入到有序子集list[0]中,构成新的有序子集list[0]:list[1]:当list[1] < list[0]时,将list[0]和list[1]互换,否则list[0]和的位置不变。
...
第i次遍历,将list[i]插入到有序子集list[0]:list[i - 1]中,构成新的有序子集list[0]:list[i]:先查找list[i]应试插入的位置,设为j,将list[j]到list[i - 1]中的元素往后移一个位置,将list[i]插入到位置j.
...
第n次遍历,将list[n]插入到有序子集list[0]:list[n-1]中,插入方法同上,这里就不再哆嗦了。
好了,根据上面的算法,我们开始编码了:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace CYB.DataStruct.Sorting
- {
- /// <summary>
- /// 作者 : cyb
- /// 发表时间 : 2008-9-8
- /// qq : 13101908
- /// e-mail : hustcyb@gmail.com
- /// </summary>
- public class InsertionSorter : Sorter
- {
- public override void Sort<T>(IList<T> list, CompareDelegate<T> compare)
- {
- base .Sort(list, compare);
- for ( int endIndex = 1; endIndex < list.Count; endIndex++)
- {
- T temp = list[endIndex]; //待插入的元素
- int index = endIndex - 1;
- while (index >= 0 && compare(list[index], temp) > 0)
- {
- list[index + 1] = list[index]; //将有序子集中大于temp的元素往后移一个位置
- index--;
- }
- list[index + 1] = temp; //将待插入的元素插入到合适的位置,构造新的有序子集
- }
- }
- }
- }