Grupo
Arrays y Vectores en C++
Ojetivo
1. Crea una función que tome un array y su tamaño como entrada.
2. Implementa un algoritmo de ordenamiento para reorganizar los números en orden ascendente.
3. Puedes usar un algoritmo de ordenamiento simple como el Ordenamiento de Burbuja.
4. Imprime el array ordenado para verificar el resultado.
5. Asegúrate de que la salida muestre los números de menor a mayor.
Crea un programa que ordene un array de números de menor a mayor.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// Function to sort an array in ascending order using Bubble Sort
void sortArray(int arr[], int size) {
// Loop through each element in the array
for (int i = 0; i < size - 1; i++) {
// Loop through the array again, up to the last unsorted element
for (int j = 0; j < size - i - 1; j++) {
// If the current element is greater than the next, swap them
if (arr[j] > arr[j + 1]) {
// Swap the elements
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) {
// Loop through the array and print each element
for (int i = 0; i < size; i++) {
cout << arr[i] << " "; // Print each number followed by a space
}
cout << endl; // Print a newline after the array
}
int main() {
// Define an array of numbers to be sorted
int numbers[] = {34, 12, 5, 9, 27, 43};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
// Call the sorting function
sortArray(numbers, size);
// Print the sorted array
cout << "Sorted array: ";
printArray(numbers, size);
return 0; // End of program
}
Salida
Sorted array: 5 9 12 27 34 43
Comparte este ejercicio C++