Java Program to Perform Bubble Sort on Strings

Write a Java program to perform bubble sort on string array items using for loop. To perform the bubble sort, we have to compare the adjacent strings and swap them if they are not in ascending order.

package RemainingSimplePrograms;

public class BubbleSortString1 {

	public static void main(String[] args) {
		int i, j;
		
		String[] str = {"Java", "Python", "C", "SQL", "Tableau"};
		
		String temp;
		
		System.out.println("Sorting String using the Bubble Sort");
		for(i = 0; i < str.length; i++)
		{
			for(j = 0; j < str.length - i - 1; j++)
			{
				if(str[j + 1].compareTo(str[j]) > 0)
				{
					temp = str[j];
					str[j] = str[j + 1];
					str[j + 1] = temp;
				}
			}
			System.out.println(str[j]);
		}
	}
}
Java Program to Perform Bubble Sort on Strings

It is another example to Perform Bubble Sort on Strings.

package RemainingSimplePrograms;

public class BubbleSortString2 {

	public static void main(String[] args) {
		int i, j;
		String[] str = {"Java", "Python", "C", "SQL", "Tableau"};
		String temp;
		
		for(j = 0; j < str.length; j++)
		{
			for(i = j + 1; i < str.length; i++)
			{
				if(str[i].compareTo(str[j]) < 0)
				{
					temp = str[j];
					str[j] = str[i];
					str[i] = temp;
				}
			}
			System.out.println(str[j]);
		}
	}
}
C
Java
Python
SQL
Tableau