Bubble Sort on Strings example
In the following example we have stored the strings in a String array and we are using nested for loops to compare adjacent strings in the array, if they are not in order we are swapping them using a temporary string variable temp.
Here we are using compareTo() method to compare the adjacent Strings.
public class JavaExample {
public static void main(String []args) {
String str[] = { "Ajeet", "Steve", "Rick", "Becky", "Mohan"};
String temp;
System.out.println("Strings in sorted order:");
for (int j = 0; j < str.length; j++) {
for (int i = j + 1; i < str.length; i++) {
// comparing adjacent strings
if (str[i].compareTo(str[j]) < 0) {
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
System.out.println(str[j]);
}
}
}

Output:
Leave a Reply