Perform Bubble Sort on strings in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 14-Dec-2018 15:55:47
Advertisements