插入排序 (Insertion Sort)的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据, 在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。
using System; using System.Collections.Generic; namespace Com.Colobu.Algorithm.Insertion { /// <summary> /// 插入排序(Insertion Sort)的算法描述是一种简单直观的排序算法。 /// 它的工作原理是通过构建有序序列,对于未排序数据, /// 在已排序序列中从后向前扫描,找到相应位置并插入。 /// 插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序), /// 因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位, /// 为最新元素提供插入空间。 /// /// 平均时间复杂度:O(n^2) /// Stability:Yes /// </summary> public class InsertionSortAlgorithm { public static void InsertionSort<T>(IList<T> szArray) where T : IComparable { int count = szArray.Count; int j; T temp; for (int i = 1; i < count; i++) { temp = szArray[i];//store the original sorted array in temp for (j = i; j > 0 && (temp.CompareTo(szArray[j - 1]) < 0); j--)//compare the new array with temp { szArray[j] = szArray[j - 1];//all larger elements are moved one pot to the right } szArray[j] = temp; } } } }
博客园 © 2004-2025 浙公网安备 33010602011771号 浙ICP备2021040463号-3