java - Generic Binary Search Using String -
i have generic binary search functions integers
in array
. however, when applied array
of strings
return @ 3 of indexes correctly ([1],[2],[3]), while marking others nonexistent ([-1]). in advance insight.
public class binarysearch { private binarysearch() { } private static <t extends comparable<? super t>> int search(t[] list, int first, int last, t key){ int foundposition; int mid = first + (last - first) / 2; if (first > last) foundposition = -1; else if (key.equals(list[mid])) foundposition = mid; else if (key.compareto(list[mid]) < 0) foundposition = search(list, first, mid - 1, key); else foundposition = search(list, mid + 1, last, key); return foundposition; } public static void main(string args[]) { //integer integer [] searchinteger = {0,2,4,6,8,10,12,14,16}; int integerlast = searchinteger.length-1; system.out.println("integer test array contains..."); (integer a1 : searchinteger) { system.out.print(a1 + " "); } system.out.println("\nchecking integer array..."); int result; (int key = -4; key < 18; key++) { result = binarysearch.search(searchinteger, 0, integerlast, key); if (result < 0) system.out.println(key + " not in array."); else system.out.println(key + " @ index " + result + "."); } //string string[] searchfruits = {"lemon", "apple", "banana", "peach", "pineapple", "grapes", "blueberry", "papaya"}; system.out.println("string test array contains..."); (string a1 : searchfruits) { system.out.print(a1 + " "); } system.out.println("\nchecking string array..."); int results; int fruitlast = searchfruits.length-1; (int key = 0; key < searchfruits.length; key++){ results = binarysearch.search(searchfruits, 0, fruitlast, searchfruits[key]); system.out.println("key = " + searchfruits[key]); system.out.println("index result = " + results); if (results < 0) system.out.println(searchfruits[key] + " not in array."); else system.out.println(searchfruits[key] + " @ index " + results + "."); } } }
because string array
string[] searchfruits = {"lemon", "apple", "banana", "peach", "pineapple", "grapes", "blueberry", "papaya"};
is not sorted, integer array
integer [] searchinteger = {0,2,4,6,8,10,12,14,16};
is sorted.
by way have used arrays.binarysearch() too.
Comments
Post a Comment