|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strings" |
| 6 | +) |
| 7 | + |
| 8 | +// Given a list of sorted words (strings with no spaces), |
| 9 | +// search for a user provided word in the list without |
| 10 | +// being case sensitive. Return -1 if the word isn't found |
| 11 | +// and return the index of the word if it is found. |
| 12 | +func main() { |
| 13 | + var words []string = []string{ |
| 14 | + "ALLigator", |
| 15 | + "bat", |
| 16 | + "bEEtle", |
| 17 | + "camel", |
| 18 | + "cat", |
| 19 | + "cheetah", |
| 20 | + "COLT", |
| 21 | + "cow", |
| 22 | + "dog", |
| 23 | + "eagle", |
| 24 | + "froG", |
| 25 | + "hamster", |
| 26 | + "horse", |
| 27 | + "mink", |
| 28 | + "moose", |
| 29 | + "porcupine", |
| 30 | + "RaT", |
| 31 | + "rooster", |
| 32 | + "steer", |
| 33 | + } |
| 34 | + fmt.Println("Sorted Words:", words) |
| 35 | + var toFind string |
| 36 | + fmt.Println("What word should we search for? No spaces please!") |
| 37 | + fmt.Scanf("%s", &toFind) |
| 38 | + var index int |
| 39 | + index = binSearch(words, toFind) |
| 40 | + if index < 0 { |
| 41 | + fmt.Println("The word", toFind, "could not be found!") |
| 42 | + } else { |
| 43 | + fmt.Println("The word", toFind, "was found at index:", index, words[index]) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +func binSearch(words []string, word string) int { |
| 48 | + var lo int = 0 |
| 49 | + var hi int = len(words) - 1 |
| 50 | + |
| 51 | + for lo <= hi { |
| 52 | + var mid int = lo + (hi-lo)/2 |
| 53 | + var midValue string = words[mid] |
| 54 | + |
| 55 | + if compare(midValue, word) == 0 { |
| 56 | + return mid |
| 57 | + } else if compare(midValue, word) > 0 { |
| 58 | + // We want to use the left half of our list |
| 59 | + hi = mid - 1 |
| 60 | + } else { |
| 61 | + // We want to use the right half of our list |
| 62 | + lo = mid + 1 |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + // If we get here we tried to look at an invalid sub-list |
| 67 | + // which means the number isn't in our list. |
| 68 | + return -1 |
| 69 | +} |
| 70 | + |
| 71 | +func compare(a, b string) int { |
| 72 | + var aLow string = strings.ToLower(a) |
| 73 | + var bLow string = strings.ToLower(b) |
| 74 | + if aLow == bLow { |
| 75 | + return 0 |
| 76 | + } else if aLow < bLow { |
| 77 | + return -1 |
| 78 | + } else { |
| 79 | + return 1 |
| 80 | + } |
| 81 | +} |
0 commit comments