Group
Search and Sort Algorithms in C++
Objective
Write a C++ function to sort an array of strings alphabetically using the Bubble Sort algorithm. The function should compare adjacent strings and swap them if they are in the wrong order, repeating the process until the entire array is sorted.
Create a function that sorts strings alphabetically using the Bubble Sort method.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the input-output stream library
#include <string> // Include the string library for handling strings
#include <vector> // Include the vector library to use dynamic arrays
using namespace std;
// Function to perform Bubble Sort on an array of strings
void bubbleSort(vector<string> &arr) {
int n = arr.size(); // Get the size of the array
// Outer loop to traverse through all elements
for (int i = 0; i < n - 1; i++) {
// Inner loop for comparison and swapping adjacent elements
for (int j = 0; j < n - i - 1; j++) {
// Compare adjacent strings
if (arr[j] > arr[j + 1]) {
// Swap the strings if they are in the wrong order
string temp = arr[j]; // Temporary variable for swapping
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
// Define an array of strings
vector<string> arr = {"Banana", "Apple", "Orange", "Mango", "Peach"};
// Call the bubbleSort function to sort the array
bubbleSort(arr);
// Display the sorted array
cout << "Sorted array: ";
for (const string &str : arr) {
cout << str << " "; // Print each string in the sorted array
}
cout << endl;
return 0;
}
Output
Sorted array: Apple Banana Mango Orange Peach