// 二分法 // 根据给出的Key得到Value // return: // -1 not found public int Search(string strKeyParam, out string strValue) { strValue = ""; int k; // 区间左 int m; // 区间右 int j = -1; // 区间中 string strKey; int nComp; k = 0; m = (int)this.Count - 1; while (k <= m) { j = (k + m) / 2; // 取得j位置的值 CharsetItem item = (CharsetItem)this[j]; strKey = item.Name; nComp = String.Compare(strKey, strKeyParam); if (nComp == 0) { strValue = item.Value; break; } if (nComp > 0) { // strKeyParam较小 m = j - 1; } else { k = j + 1; } } if (k > m) { return(-1); // not found } return(j); }
// 实现IComparable接口的CompareTo()方法, // 根据ID比较两个对象的大小,以便排序, // 按右对齐方式比较 // obj: An object to compare with this instance // 返回值 A 32-bit signed integer that indicates the relative order of the comparands. The return value has these meanings: // Less than zero: This instance is less than obj. // Zero: This instance is equal to obj. // Greater than zero: This instance is greater than obj. // 异常: ArgumentException,obj is not the same type as this instance. public override int CompareTo(object obj) { CharsetItem item = (CharsetItem)obj; return(String.Compare(this.Name, item.Name)); }