C#排序算法——插入法

  在阅读此博文前,请先阅读我的博文“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]中,插入方法同上,这里就不再哆嗦了。
  好了,根据上面的算法,我们开始编码了:

  1. using  System;
  2. using  System.Collections.Generic;
  3. using  System.Text;
  4. namespace  CYB.DataStruct.Sorting
  5. {
  6.      /// 
  7.      /// 作者 : cyb
  8.      /// 发表时间 : 2008-9-8
  9.      /// qq : 13101908
  10.      /// e-mail : [email protected]
  11.      /// 
  12.      public   class  InsertionSorter : Sorter
  13.     {
  14.          public   override   void  Sort(IList list, CompareDelegate compare)
  15.         {
  16.              base .Sort(list, compare);
  17.              for  ( int  endIndex = 1; endIndex < list.Count; endIndex++)
  18.             {
  19.                 T temp = list[endIndex];   //待插入的元素
  20.                  int  index = endIndex - 1;
  21.                  while  (index >= 0 && compare(list[index], temp) > 0)
  22.                 {
  23.                     list[index + 1] = list[index];   //将有序子集中大于temp的元素往后移一个位置
  24.                     index--;
  25.                 }
  26.                 list[index + 1] = temp;      //将待插入的元素插入到合适的位置,构造新的有序子集
  27.             }
  28.         }
  29.     }
  30. }


你可能感兴趣的:(C#数据结构)