`
javatome
  • 浏览: 825288 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

二分查找排序

 
阅读更多

二分查找排序可以认为是插入排序的一个变种,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;

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics