From 2a1169c472e44743648aea80ed10f6d20d184ec3 Mon Sep 17 00:00:00 2001 From: Aidan WU Date: Mon, 7 Oct 2013 18:15:39 -0400 Subject: [PATCH] Update 9.5.cpp --- 9.5.cpp | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/9.5.cpp b/9.5.cpp index b34a6f5..a38b336 100644 --- a/9.5.cpp +++ b/9.5.cpp @@ -2,20 +2,39 @@ using namespace std; int search(string s[], int low, int high, string x){ + if(low > high) return -1; if(x == "") return -1; - while(low <= high){ - int mid = (low+high)>>1; - int t = mid; - while(s[t] == "" && t <= high) ++t; - if(t > high) high = mid - 1; - else{ - if(s[t] == x) return t; - else if(s[t] < x) low = t + 1; - else high = mid - 1; //or t-1, (mid, t)为空字符串 + //Move mid to the middle + int mid = (low + high) / 2; + //If mid is empty, find closest non-empty string + if(s[mid] == ""){ + int left = mid - 1; + int right = mid + 1; + while(true){ + if(left < low && right > high){ + return -1; + } else if(right <= high && s[right] != ""){ + mid = right; + break; + } else if(left >= low && s[left] != ""){ + mid = left; + break; + } + right++; + left--; } } - return -1; + + //Check for string, and recurse if necessary + if(x == s[mid]){ + return mid; + } else if(s[mid] < x){ + return search(s, mid + 1, high, x); + } else{ + return search(s, low, mid - 1, x); + } } + int main(){ string s[13] = { "at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""