二分查找排序可以认为是插入排序的一个变种,C#代码如下,需要先写一个帮助方法Insert(),以备排序时插入所用:
public static int[] Insert(int[] array,int targetIndex,int currentIndex)
{
int value = array[currentIndex];
for (int i = currentIndex; i > targetIndex; i--)
{
array[i] = array[i - 1];
}
array[targetIndex] = value;
return array;
}
public static int[] InsertSort(int[] array)
{
int startIndex;
int endIndex;
int middle;
for (int i = 1; i < array.Length; i++)
{
startIndex = 0;
endIndex = i-1;
while (startIndex - endIndex > 1)
{
middle = ((startIndex + endIndex) - (startIndex + endIndex) % 2) / 2;
if (array[i] > array[middle])
{
startIndex = middle;
}
else
{
endIndex = middle;
}
}
if (array[i] <= array[startIndex])
{
Insert(array, startIndex, i);
}
else if (array[i] >= array[endIndex])
{
Insert(array, endIndex + 1, i);
}
else
{
Insert(array, endIndex, i);
}
}
return array;
}