Jump to content

About binary search in Java....


albertlee

Recommended Posts

import java.util.TreeSet;
import java.util.ArrayList;
import java.util.Iterator;

public class Sort {
TextWindow tw = new TextWindow("Sort");
String array[] = {
"cow", "dog", "horse", "moose", "lynx", "rabbit",
"bear", "cat", "bird", "wolf", "elk", "reindeer"
};
ArrayList<String> list;
public static void main(String arg[]) {
Sort sort = new Sort();
sort.arrayToList();
sort.searchList("moose");
sort.listToArray();
sort.searchArray("moose");
}
public void arrayToList() {
[b]TreeSet<String> set = new TreeSet<String>();
for(String animal: array)
set.add(animal);[/b]
list = new ArrayList<String>();
Iterator<String> iterator = set.iterator();
while(iterator.hasNext()) {
String animal = iterator.next();
list.add(animal);
}
}
public void searchList(String animal) {
int low = 0;
int high = list.size() - 1;
while(low <= high) {
int mid = (low + high) / 2;
String current = list.get(mid);
if(animal.compareTo(current) < 0)
high = mid - 1;
else if(animal.compareTo(current) > 0)
low = mid + 1;
else {
tw.line("searchList found " + animal + " at position " + mid);
return;
}
}
tw.line("searchList did not find " + animal);
}
public void listToArray() {
array = list.toArray(array);
}
public void searchArray(String animal) {
int low = 0;
int high = array.length - 1;
while(low <= high) {
int mid = (low + high) / 2;
String current = array[mid];
if(animal.compareTo(current) < 0)
high = mid - 1;
else if(animal.compareTo(current) > 0)
low = mid + 1;
else {
tw.line("searchArray found " + animal + " at position " + mid);
return;
}
}
tw.line("searchArray did not find " + animal);
}
}

 

My question is, isn't the bold portion of the code redundant? why not just extract every item of the array and add it to the list?

 

I was told that TreeSet automatially orders the input items by natural object order, is that true? I read the offical java tutorial, and it only says that TreeSet, as opposed to HashSet, guarantees order of items, but now the term "order" confuses me... does it mean "natural order" or simply just the sequence of item you add to it?

 

please help me.....

 

thanks

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.