Ai
1 Star 1 Fork 0

AndyZhang/C-Sharp-Algorithms

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
InsertionSorter.cs 1.89 KB
一键复制 编辑 原始数据 按行查看 历史
Nicholas Rodine 提交于 2018-02-08 02:38 +08:00 . Removed unused usings (#61)
using System.Collections.Generic;
using DataStructures.Lists;
namespace Algorithms.Sorting
{
/// <summary>
/// Implements this Insertion Sort algorithm over ArrayLists.
/// </summary>
public static class InsertionSorter
{
//
// The quick insertion sort algorithm.
// For any collection that implements the IList interface.
public static void InsertionSort<T>(this IList<T> list, Comparer<T> comparer = null)
{
//
// If the comparer is Null, then initialize it using a default typed comparer
comparer = comparer ?? Comparer<T>.Default;
// Do sorting if list is not empty.
int i, j;
for (i = 1; i < list.Count; i++)
{
T value = list[i];
j = i - 1;
while ((j >= 0) && (comparer.Compare(list[j], value) > 0))
{
list[j + 1] = list[j];
j--;
}
list[j + 1] = value;
}
}
//
// The quick insertion sort algorithm.
// For the internal ArrayList<T>. Check the DataStructures.ArrayList.cs.
public static void InsertionSort<T>(this ArrayList<T> list, Comparer<T> comparer = null)
{
//
// If the comparer is Null, then initialize it using a default typed comparer
comparer = comparer ?? Comparer<T>.Default;
for (int i = 1; i < list.Count; i++)
{
for (int j = i; j > 0; j--)
{
if (comparer.Compare(list[j], list[j - 1]) < 0) //(j)th is less than (j-1)th
{
var temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
}
}
}
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/strongandyzhang/C-Sharp-Algorithms.git
git@gitee.com:strongandyzhang/C-Sharp-Algorithms.git
strongandyzhang
C-Sharp-Algorithms
C-Sharp-Algorithms
master

搜索帮助