Perform Bubble Sort on strings in Java


To perform Bubble Sort, try the below given code. In this each each pair of adjacent elements is compared and the elements are swapped if they are not in order.

The following is an example.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      String str[] = { "s", "k", "r", "v", "n"};
      String temp;
      System.out.println("Sorted string...");
      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(str[j]);
      }
   }
}

Output

Sorted string...
k
n
r
s
v

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 27-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements