In this program I just wanted to bubble sort the ArrayList
words
. So far I used the Collections.sort
and it has placed all the lines in the text file alphabetically. However, I want to implement a binary search algorithm to this program but, I don't think it would be possible to do so without sorting the data (e.g merge sort, bubble sort). I might be wrong but that is why I came here for guidance & knowledge.
Secondly, when I create a method for sorting, this is a words
is a String
not an String[]
. How do I then do a bubble sort using such a datatype?
public static void main(String[]args) throws IOException{
Scanner scan = new Scanner(System.in);
String stringSearch = scan.nextLine();
ArrayList<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("File1.txt"));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}reader.close();
Collections.sort(words);
for(String str:words)
System.out.println(str);
for(String sLine : words)
{
if (sLine.contains(stringSearch))
{
int index = words.indexOf(sLine);
System.out.println("Got a match at line " + index);
}
}
System.out.println(words.size());
}
First, you can sort the list using Collections.sort(Collection).
Second, you can use List.get(int) of the ArrayList implementation to achieve an O(1) indexed access.
Third, Object.compareTo(Object) will do the job of guiding your binary search loop.
Sorry if I misunderstood something!