C#中插入排序
class Program
{
static void Main(string[] args)
{
int[] array = new[] { 234, 632, 23, 643, 2, 6, -2, 423, 2342,43 };
Console.WriteLine("排序前:");
Console.WriteLine(string.Join(",", array));
InsertSort(array);
Console.WriteLine("排序后:");
Console.WriteLine(string.Join(",", array));
Console.ReadKey();
}
/// <summary>
/// 直接插入排序
/// </summary>
/// <param name="sources">目标数组</param>
private static void InsertSort(int[] sources)
{
// 从索引1开始,假设sources已经有序
for (int i = 1, len = sources.Length - 1; i <= len; i++)
{
// 准备要插入的数据
int insertValue = sources,
// 假设要插入的索引
insertIndex = i - 1;
// 遍历查找插入的索引位置
while (insertIndex >= 0 && insertValue < sources)
{
// 当前数据后移一位
sources = sources;
insertIndex--;
}
// 不满足以上条件,说明找到位置,插入数据
sources = insertValue;
}
}
/// <summary>
/// 直接插入排序 for实现
/// </summary>
/// <param name="sources">目标数组</param>
private static void InsertSort1(int[] sources)
{
for (int i = 1, len = sources.Length - 1; i <= len; i++)
{
for (int j = i; j > 0; j--)
{
if (sources > sources) // > 降序, < 升序
{
int temp = sources;
sources = sources;
sources = temp;
}
}
}
}
}
111 222 4444
页:
[1]