java - How do I get a generic version of the binary search algorithm to find elements in list -



java - How do I get a generic version of the binary search algorithm to find elements in list -

i've got wrong search method.

public int search(t element) { int start = 0; int end = elements.length - 1; while (start <= end) { int middle = ((start + end) / 2); int result = element.compareto(elements[middle]); if (result < 0) { start = middle - 1; } else if (result > 0) { end = middle + 1; } else { homecoming middle; } } homecoming -1; }

my main method consists of array, need phone call search metho , have print out element ins list.

public static void main(string[] args) { string[] states = {"tennessee", "north carolina", "kentucky", "georgia", "florida", "washington", "new york", "vermont", "oregon", "wyoming"}; genericbinarysearchtree<string> sts = new genericbinarysearchtree<string>(states); system.out.println("vermont #" + sts.search("vermont") + " element in list!"); system.out.println("kentucky #" + sts.search("kentucky") + " element in list!"); }

it can't find values. instance, output vermont , kentucky:

vermont #7 element in list! kentucky #-1 element in list! ----jgrasp: operation complete.

i have tried kinds of different things , looked @ many examples still won't work properly.

here class:

class genericbinarysearchtree<t extends comparable<t>> { private t[] elements; /* **constructs empty tree. */ public genericbinarysearchtree(t[] names) { elements = names; } public int search(t element) { int start = 0; int end = elements.length - 1; while (start <= end) { int middle = ((start + end) / 2); int result = element.compareto(elements[middle]); if (result < 0) { end = middle - 1; } else if (result > 0) { start = middle + 1; } else { homecoming middle; } } homecoming -1; }

}

java binary-search

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -