Grupo
Algoritmos de Búsqueda y Ordenación en C++
Ojetivo
Cree una función llamada selectionSort que tome como parámetros un array de enteros y su tamaño. Implemente la lógica para encontrar el elemento mínimo en cada pasada e intercambiarlo con el elemento actual. En la función principal, defina un array sin ordenar, aplique la función selectionSort para ordenarlo y luego imprima el array ordenado.
Escriba una función que ordene un array mediante el algoritmo de ordenamiento por selección.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include input-output stream library
using namespace std;
// Function to perform selection sort
void selectionSort(int arr[], int n) {
// Traverse the entire array
for (int i = 0; i < n - 1; i++) {
int minIndex = i; // Assume the current index has the smallest value
// Search for the smallest element in the unsorted part
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j; // Update index if smaller element is found
}
}
// Swap the found minimum element with the first unsorted element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
// Main function
int main() {
// Define an unsorted array
int arr[] = {29, 10, 14, 37, 13};
int size = sizeof(arr) / sizeof(arr[0]); // Calculate the array size
// Call the selectionSort function to sort the array
selectionSort(arr, size);
// Print the sorted array
cout << "Sorted array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0; // End of program
}
Salida
Sorted array: 10 13 14 29 37
Comparte este ejercicio C++