Java Program to perform bubble sort on string

Here we are explaining how to write a java program to perform bubble sort on a string. Here first we declare a string array to hold the strings. Then by using a nested for loop compare the strings with the adjacent strings. Swap the strings if they are not in sorted order.

How to compare strings in java?

We can compare the strings by using CompareTo() method.

The CompareTo() function returns zero , if both the strings are equal.

The function returns a negative value if the first string is less than the second string.

The function returns a positive value if the first string is greater than the second one.

How to implement the java program to perform bubble sort on a string?

First, we have to declare the class BubbleSort.Then open the main function.Declare string array s[],and assign some values.Declare a temporary string variable t.By using nested for loop check the adjacent strings using the method compareTo(). If the function returns a negative value then swap the elements. Then display the array elements as sorted strings.

ALGORITHM

STEP 1: Declare the class BubbleSort with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare a string array s[] with strings.

STEP 4: Declare a temporary variable t.

STEP 5: By using a for loop with the condition j

STEP 6: By using another for loop set i=j+1, with the condition i

STEP 7: Check if s[i]

STEP 8: Display the sorted string as s.

 

Java Source Code

                                          public class BubbleSort {
    public static void main(String[] args) {
        String s[] = {
            "Mahesh",
            "Rithesh",
            "Veena",
            "Preethu",
            "Abi"
        };
        String t;
        System.out.println("Sorted Strings:");
        for (int j = 0; j < s.length; j++) {
            for (int i = j + 1; i < s.length; i++) {

                if (s[i].compareTo(s[j]) < 0) {
                    t = s[j];
                    s[j] = s[i];
                    s[i] = t;
                }
            }
            System.out.println(s[j]);
        }
    }
}
                                      

OUTPUT

Sorted Strings:
Abi
Mahesh
Preethu
Rithesh
Veena