Reputation: 21
I am trying to use two for loops to sort a list of strings alphabetically.
Specifically I am not allowed to use java.util.Collections.sort()
.
for(int i = 0; i < str.size(); i++)
{
for (int j = i+1; j < str.size(); j++)
{
if(str.get(i).compareTo(str.get(j))< 0)
{
String temp;
str.add(temp);
str.set(str.get(temp),str.get(i));
str.set(i, str.get(j));
}
}
}
Here is what I have so far. The idea is that it could work with any list. The main problem I keep getting is how to add a temporary string in order to retain the data in i
and j
.
Upvotes: 2
Views: 2760
Reputation: 1778
You don't want to add the temporary string to the arraylist you are sorting - you should use it to swap the two values instead:
String temp = str.get(i);
str.set(i, str.get(j)); // this overwrites str.get(i),
// hence the need for temp
str.set(j, temp);
Also, what you are doing is not really bubble sort :-)
Wikipedia has nice articles on the most common algorithms/problems and is a great resource for starting with programming, for example https://en.wikipedia.org/wiki/Bubble_sort
Welcome to the programming bunch!
Upvotes: 3
Reputation: 976
Here is the code. It is good to see that you have tried something on your own before coming here. There are other sorting techniques that are faster than Bubble Sort. Please try them if possible.
List<String> str = new ArrayList<>();
str.add("bbbb");
str.add("aaaa");
str.add("cccc");
for(int i = 0; i < str.size(); i++)
{
for (int j = i+1; j < str.size(); j++)
{
if(str.get(i).compareTo(str.get(j))< 0)
{
String temp = str.get(i);
str.set(i, str.get(j));
str.set(j, temp);
}
}
}
System.out.println(str); //this will print cccc,bbbb,aaaa
Upvotes: 0