java - How to get more search data using binary search? -
first of apologize english language , first time asking on stackoverflow if miss please point out.
so i'm new java , trying out binary search help friend. code display product info 1 time searched product id. manage create homecoming index number id found problem when set in multiple same id show 1 data. want programme show index id-12 found.
import java.util.arraylist; import java.util.collections; import java.util.comparator; import java.util.list; public class mylistbinarysearch { public static void main(string a[]){ list<emp> emplist = new arraylist<emp>(); emplist.add(new emp(12,"apple,50,10-5-2014")); emplist.add(new emp(12,"apple,50,5-5-2014")); emplist.add(new emp(124,"apple,50,2-5-2014")); emplist.add(new emp(302,"apple,50,2-5-2014")); emplist.add(new emp(12,"apple,50,2-5-2014")); emp searchkey = new emp(12,"string"); int index = collections.binarysearch(emplist, searchkey, new empcomp()); system.out.println("index of searched key: "+index); } } class empcomp implements comparator<emp>{ public int compare(emp e1, emp e2) { if(e1.getempid() == e2.getempid()){ homecoming 0; } else { homecoming -1; } } } class emp { private int empid; private string empinfo; public emp(int id, string info){ this.empid = id; this.empinfo = info; } public int getempid() { homecoming empid; } public void setempid(int empid) { this.empid = empid; } public string getempinfo() { homecoming empinfo; } public void setempinfo(string empinfo) { this.empinfo = empinfo; } @override public string tostring(){ homecoming empid+" : "+empinfo; } }
the out "index of searched key: 2" want display index search key found. how do ? need loop ?
you have 2 problems:
your comparator should homecoming greater 0 when current element greater compared element, 0 when elements equals , less 0 when current element less compared element. current implementation doesn't cover this. binary search works on sorted arrays/lists only. list not sorted id.after fixing issues, utilize binary search. after retrieving index element 12, can search around element retrieve elements have same id.
this thought how implement it:
int index = collections.binarysearch(emplist, searchkey, new empcomp()); list<emp> empswithid12 = new arraylist<emp>(); (int = index - 1; >= 0; i--) { emp emp = emplist.get(i); if (emp.getid() == 12) { empswithid12.add(emp); } else { break; } } collections.reverse(empswithid12); (int = index; < emplist.size(); i++) { emp emp = emplist.get(i); if (emp.getid() == 12) { empswithid12.add(emp); } else { break; } }
note thought above can improved moving logic method.
java arrays search indexing
No comments:
Post a Comment