Bubble Sort on Strings – Java

Java program on bubble sort

- Advertisement -

To perform bubble sort on Strings we need to compare adjacent Strings and if they are not in the order then we need to swap those strings, this process needs to be done until we reach at the end. This way all the strings will be sorted in ascending order, this process of sorting is known as bubble sorting.

- Advertisement -

public class JavaExample {
   public static void main(String []args) {
	String str[] = { "Ajeet", "Steve", "Rick", "Becky", "Mohan"};
	String temp;
	System.out.println("Strings in sorted order:");
	for (int j = 0; j < str.length; j++) {
   	   for (int i = j + 1; i < str.length; i++) {
		// comparing adjacent strings
		if (str[i].compareTo(str[j]) < 0) {
			temp = str[j];
			str[j] = str[i];
			str[i] = temp;
		}
	   }
	   System.out.println(str[j]);
	}
   }
}

 

 

 

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More