插入排序简单实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InsertionSort
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 1, 5, 3, 6, 2, 9 };
int key;
int j;
int tmp;
for (int i = 1; i < arr.Length; ++i )
{
key = arr[i];
// 将数值插入到合适位置
j = i - 1;
while ( (j > 0) && (arr[j] > key) ) // 升序
{
// 移动数据
arr[j + 1] = arr[j];
--j;
}
// 找到了新加入的元素
arr[j + 1] = key;
}
foreach (int item in arr)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InsertionSort
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 1, 5, 3, 6, 2, 9 };
int key;
int j;
int tmp;
for (int i = 1; i < arr.Length; ++i )
{
key = arr[i];
// 将数值插入到合适位置
j = i - 1;
while ( (j > 0) && (arr[j] > key) ) // 升序
{
// 移动数据
arr[j + 1] = arr[j];
--j;
}
// 找到了新加入的元素
arr[j + 1] = key;
}
foreach (int item in arr)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
如果您觉得不错,欢迎扫码支持下。
作者:许强1. 本博客中的文章均是个人在学习和项目开发中总结。其中难免存在不足之处 ,欢迎留言指正。 2. 本文版权归作者和博客园共有,转载时,请保留本文链接。