Grupo
Algoritmos de Búsqueda y Ordenación en C++
Ojetivo
Escriba una función en C++ para ordenar alfabéticamente un array de cadenas mediante el algoritmo de ordenamiento de burbuja. La función debe comparar cadenas adyacentes e intercambiarlas si están en el orden incorrecto, repitiendo el proceso hasta que todo el array esté ordenado.
Cree una función que ordene las cadenas alfabéticamente mediante el método de ordenamiento de burbuja.
Ejemplo de Código C++
Mostrar Código C++
#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;
}
Salida
Sorted array: Apple Banana Mango Orange Peach
Comparte este ejercicio C++