/*** Function: There is an array of sorted strings, which scatter some empty strings to find the position of the given string. */
/** * Idea: Make changes to the binary lookup method, and, if mid is an empty string, swap the mid to the position of the non-empty string closest to it, as compared to mid. * @param strings * @param str * @return */public static int search (string[] strings,string str) {if (strings==null| | str==null| | str== "") Return-1;return Searchstr (strings,str,0,strings.length);} public static int Searchstr (string[] strings,string str,int First,int last) {if (first>last) Return-1;int mid= (first+ Last)/2;//if mid is an empty string, find out the nearest non-empty string if (Strings[mid].isempty ()) {int Left=mid-1;int right=mid+1;while (true) {if (left <first&&right>last) Return-1;else if (Right<last&&!strings[right].isempty ()) {mid=right; break;} else if (Left>first&&!strings[left].isempty ()) {mid=left;break;} left--;right++;}} if (Str.equals (Strings[mid])) return Mid;else if (Strings[mid].compareto (str) <0) return Searchstr (strings, str, mid+ 1, last);//Search Right Half Elsereturn searchstr (strings, str, first, mid-1);//search left Half}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
9.11 Sorting and Finding (v)--there is an array of sorted strings, which scatter some empty strings to find the position of the given string