Bubble Sort in String Program in Java

Bubble Sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. This process is repeated until no more swaps are needed, which means the list is sorted.

import java.util.Scanner;
public class BubbleSortString
{
    public static void main(String[] args)
    {
        String temp;
        String str[] = new String[10];
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 10; i++)
        {
            System.out.print("Enter the string ar[" + i + "]:");
            str[i] = sc.nextLine();
        }
        for (int j = 0; j < str.length; j++)
        {
            for (int i = j + 1; i < str.length; i++)
            {
                // comparing strings
                if (str[i].compareTo(str[j]) < 0)
                {
                    temp = str[j];
                    str[j] = str[i];
                    str[i] = temp;
                }
            }
        }
        System.out.println("Sorted order:");
        for (int i = 0; i < 10; i++)
        {
            System.out.println(str[i]);
        }
    }
}


Output:

Enter the string ar[0]:as
Enter the string ar[1]:df
Enter the string ar[2]:ew
Enter the string ar[3]:re
Enter the string ar[4]:we
Enter the string ar[5]:ds
Enter the string ar[6]:cf
Enter the string ar[7]:gf
Enter the string ar[8]:hg
Enter the string ar[9]:yj
Sorted order:
as
cf
df
ds
ew
gf
hg
re
we
yj
java tutorials learn java study java