This is a simple Java program that demonstrates the bubble sort algorithm applied to an array of strings. The program sorts the strings in ascending alphabetical order.
The BubbleSortStrings
class contains a main method that:
- Initializes an array of strings.
- Displays the original array.
- Sorting the array using the bubble sort algorithm.
- Displays the sorted array.
The bubble sort algorithm compares adjacent elements and swaps them if they are in the wrong order, repeating this process until the array is sorted.
- Java 17
- Sorting algorithm. (
Bubble Sort
) - Arrays
- Clone the repository:
git clone https://github.com/YuliyaZimenina/Bubble_Sort_For_Strings.git
cd Bubble_Sort_For_Strings
- Open the project in your favorite IDE (IntelliJ IDEA, Eclipse, etc.).
- Make sure Java 17 is set as the project SDK.
- Run the
BubbleSortStrings.java
file.
BubbleSortStrings class:
public class BubbleSortStrings {
public static void main(String[] args) {
String[] message = {
"I", "am", "sorting", "an",
"array", "of", "strings"
};
int a, b;
String t;
int size;
size = message.length; // number of elements to sort
// Display the original array
System.out.print("Original array");
for (int i = 0; i < size; i++)
System.out.print(" " + message[i]);
System.out.println();
//Bubble sort for strings
for (a = 1; a < size; a++)
for (b = size - 1; b >= a; b--) {
// If the order is not followed, then swap the elements
if (message[b - 1].compareTo(message[b]) > 0) {
t = message[b - 1];
message[b-1] = message[b];
message [b] = t;
}
}
//Display sorted array
System.out.print("Sorted array: ");
for (int i = 0; i < size; i++)
System.out.print(" " + message[i]);
System.out.println();
}
}
The result of the program: