java - Binary search on an ordered linked list -
java - Binary search on an ordered linked list -
i need help adding binary search method ordered linked list. here's code have far i'm stuck on part. i'm confused on how take values added insert method , search through , position element at. here's programme have far:
import java.util.linkedlist; class list { public list next; public list previous; public long data; public link(long d) { info = d; } public void displaylink() { system.out.print(data + " "); } } class olinklist { private linkedlist first; private linkedlist last; public olinklist() { first = null; lastly = null; } public boolean isempty() { homecoming first == null; } public void insert(long num) { list newlink = new list(num); if (first == null) { first = newlink; lastly = newlink; } else { last.next = newlink; lastly = newlink; } } }
now, have thought of how binary search works. how can take , apply code have?
public int binarysearch(int[] a, int x) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = (low + high)/2; if (a[mid] == x) homecoming mid; else if (a[mid] < x) low = mid + 1; else high = mid - 1; } homecoming -1; }
it improve either utilize array or using or implementing own treeset class. array able utilize algorithm have little better.
java binary-search
Comments
Post a Comment