C#二分查找元素及寻找要插入元素的下标

C#二分查找元素及寻找要插入元素的下标
 1 /// <summary>
 2         /// 二分查找记录以及插入的下标(前提是:要把对象数组排好序 此处为升序)
 3         /// </summary>
 4         /// <param name="value">关键值(对象中用于排序的属性值)</param>
 5         /// <param name="list">源对象数组</param>
 6         /// <param name="start">起始位置</param>
 7         /// <param name="end">结束位置</param>
 8         /// <param name="ipos">应该插入的位置</param>
 9         /// <returns>返回查找元素的位置,找不到返回-1</returns>
10         public int find2(string value, ModelList list, int start, int end,ref int ipos)
11         {
12             int temp = -1;
13             int position = -1;
14             while (start <= end)
15             {
16                 position = (start + end) / 2;//折半
17                 if (string.Compare(value, list[position].Name, true> 0)//如果要查找或要插入的元素在左半侧
18                 {
19                     start = position + 1;
20                     ipos = position+1;
21                 }
22                 else if (string.Compare(value, list[position].Name, true< 0)//如果要查找或要插入的元素在右半侧
23                 {
24                     end = position - 1;
25                     ipos = position;
26                 }
27                 else//如果找到要查找或要插入的元素 返回位置并跳出循环
28                 {
29                     temp = position;//返回所在位置
30                     ipos = position;
31                     break;
32                 }
33             }
34             return temp;
35         }


 

posted @ 2010-12-27 17:56  小胆粗心  Views(466)  Comments(0)    收藏  举报