c# - Binary Search with Strings -
i have object array , want search date / day property (user decides) using binary search.
**edit: read sharesarray[mid].date values (and day values) text file , examples are: 05/02/2015, 14/10/2014.the searchstring value gained user in same format date values. **
this first attempt trying date property:
int high, low, mid; high = sharesarray.length - 1; low = 0; while (low <= high) { mid = (low + high) / 2; if (string.compare(sharesarray[mid].date, searchstring, true) == 0) { break; } else if (string.compare(sharesarray[mid].date, searchstring, true) > 0) { high = mid - 1; } else if (string.compare(sharesarray[mid].date, searchstring, true) < 0) { low = mid + 1; }
i have tried last else if statement else , doesn't make difference.
also, matter way round string1 , string2 in string.compare part?
summarizing answer q&a in comments of question, bit of additional context.
for binary search, there few ingredients need take care of
- the input array binary search function must sorted.
- given algorithm have implemented, must sorted in ascending order.
- you must have three-way comparison function,
compare(lhs, rhs)
returns:< 0
iflhs < rhs
,> 0
iflhs > rhs
,0
iflhs == rhs
. - the order of arguments in
compare
function matters, if switch them, taking wrong branch , changing upper search bound instead of lower, or other way around. - for implementation, had order correct,
lhs
:sharesarray[mid].date
,rhs
=searchstring
. - because comparing dates, need use
datetime.compare
function, , convert date stringsdatetime
instances, usingdatetime.parseexact(mystring, "dd/mm/yyyy", cultureinfo.invariantculture);
. string comparison wrong results such"05/02/2015" < "14/10/2014"
.
and there 1 more anecdotal remark make (see here):
the calculation of pivot value mid
susceptible integer overflow. if calculate
mid = (low + high) / 2;
then low + high
become larger fits in integer.
the preferred way of calculating mid
therefore
`mid = low + ((high - low) >> 1);`.