Here we are explaining how to write a java program to perform bubble sort on a string. Bubble sort is also used to sort integer arrays, we have a program to perform bubble sort on numbers in our Java program collection, you may check that also.
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.
For a better understanding of the program, we recommend you to learn the basic topics of Java programming listed below
A bubble sort algorithm will sort the elements of an array. In bubble sort, the first element will be compared with the rest of the elements, and swapping occurs when a smaller element is obtained. So,
for loop,
1st sorted element ie., the Largest element of the array will be placed at the last indexfor loop
and we will get the fully sorted array after the final iteration.We can compare the strings using CompareTo()
method.
CompareTo()
function returns zero if both strings are equal.First, we have to declare the class BubbleSort.Then open the main function.Declare string array s_arr[],and assign some values.Declare a temporary string variable tmp.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 sorted array.
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_arr[] with strings, integer variables i,j.
STEP 4: Declare a temporary variable tmp.
STEP 5: By using a nested for loop
with the condition i < size of array and j < size of array - i -1 ( resizing the boundary or the last position till comparison should be done, after placement of each sorted element ) do step 6
STEP 6: Check if s_arr[j+1].compareTo(s_arr[j]) > 0 , means smaller string in highest index , then swap the elements as follows
STEP 7: Display the sorted string array s_arr.
public class BubbleSort {
public static void main(String[] args) {
int i,j;
String s_arr[] = {
"Richard",
"John",
"Williams",
"Peter",
"Aron"
};
String tmp;
System.out.println("Sorted Strings:");
for ( i = 0 ; i < s_arr.length ; i++) {
for ( j = 0 ; j < s_arr.length-i-1 ; j++) {
if (s_arr[j+1].compareTo(s_arr[j]) > 0) {
tmp = s_arr[j];
s_arr[j] = s_arr[j+1];
s_arr[j+1] = tmp;
}
}
System.out.println(s_arr[j]);
}
}
}
Sorted Strings: Aron John Peter Richard Williams