Grupo
Algoritmos de Búsqueda y Ordenación en C++
Ojetivo
1. Cree una función llamada bubbleSort que tome un array y su tamaño como parámetros.
2. Implemente la lógica de Bubble Sort mediante bucles anidados para comparar e intercambiar repetidamente elementos adyacentes si es necesario.
3. En la función principal, defina un array de enteros y muéstrelo antes y después de ordenarlo.
4. Utilice la salida estándar para mostrar el estado del array antes y después de aplicar el algoritmo de ordenamiento.
Implemente el algoritmo de Bubble Sort.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include for input and output operations
using namespace std;
// Function to perform Bubble Sort on an array
void bubbleSort(int arr[], int n) {
// Outer loop controls the number of passes
for (int i = 0; i < n - 1; i++) {
// Inner loop compares adjacent elements and swaps them if necessary
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements if they are in the wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Function to print the elements of the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
// Define an array of integers to be sorted
int data[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(data) / sizeof(data[0]); // Calculate the number of elements
// Display the original array
cout << "Original array: ";
printArray(data, size);
// Call the bubbleSort function to sort the array
bubbleSort(data, size);
// Display the sorted array
cout << "Sorted array: ";
printArray(data, size);
return 0; // End of program
}
Salida
Original array: 64 34 25 12 22 11 90
Sorted array: 11 12 22 25 34 64 90
Comparte este ejercicio C++