1. 直接插入排序算法:
代码
/// <summary>
/// 插入排序
/// </summary>
/// <param name="data"></param>
public static void InsertionSort(int[] data)
{
if (data == null || data.Length < 1)
{
throw new ArgumentNullException("data");
}
int temp, index;
for (int i = 1; i < data.Length; i++)
{
temp = data[i];
index = i;
while (index > 0 && temp < data[index - 1])
{
data[index] = data[--index];
}
data[index] = temp;
}
}
/// 插入排序
/// </summary>
/// <param name="data"></param>
public static void InsertionSort(int[] data)
{
if (data == null || data.Length < 1)
{
throw new ArgumentNullException("data");
}
int temp, index;
for (int i = 1; i < data.Length; i++)
{
temp = data[i];
index = i;
while (index > 0 && temp < data[index - 1])
{
data[index] = data[--index];
}
data[index] = temp;
}
}
2. 折半插入排序:
代码
/// <summary>
/// 折半插入排序
/// </summary>
/// <param name="data"></param>
public static void Bin_InsertionSort(int[] data)
{
if (data == null || data.Length < 1)
{
throw new ArgumentNullException("data");
}
int low, mid, high;
for (int i = 1; i < data.Length; i++)
{
// 折半查找
low = 0;
high = i - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (data[i] < data[mid])
{
high = mid - 1;
}
else
{
if (data[i] > data[mid])
{
low = mid + 1;
}
else
{
low = mid;
break;
}
}
}
// 移动元素
int temp = data[i];
for (int j = i; j > low; j--)
{
data[j] = data[j - 1];
}
data[low] = temp;
}
}
/// 折半插入排序
/// </summary>
/// <param name="data"></param>
public static void Bin_InsertionSort(int[] data)
{
if (data == null || data.Length < 1)
{
throw new ArgumentNullException("data");
}
int low, mid, high;
for (int i = 1; i < data.Length; i++)
{
// 折半查找
low = 0;
high = i - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (data[i] < data[mid])
{
high = mid - 1;
}
else
{
if (data[i] > data[mid])
{
low = mid + 1;
}
else
{
low = mid;
break;
}
}
}
// 移动元素
int temp = data[i];
for (int j = i; j > low; j--)
{
data[j] = data[j - 1];
}
data[low] = temp;
}
}