Grupo
Algoritmos de Búsqueda y Ordenación en C++
Ojetivo
Cree una función llamada "insertionSort" que acepte un array de enteros y su tamaño. Dentro de la función, implemente el algoritmo de ordenamiento por inserción iterando por el array e insertando cada elemento en su posición correcta dentro de la parte ordenada. En la función principal, defina un array sin ordenar y use la función "insertionSort" para ordenarlo. Finalmente, imprima el array ordenado.
Cree un programa que ordene un array usando el algoritmo de ordenamiento por inserción.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the input-output stream library
using namespace std;
// Function to perform insertion sort on an array
void insertionSort(int arr[], int size) {
// Loop through elements starting from the second one
for (int i = 1; i < size; i++) {
int key = arr[i]; // Store the current element
int j = i - 1;
// Move elements greater than key to one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j]; // Shift element to the right
j = j - 1; // Move to the previous element
}
arr[j + 1] = key; // Place the key in its correct position
}
}
int main() {
// Declare and initialize an unsorted array
int numbers[] = {9, 5, 1, 4, 3};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate array size
// Call the insertionSort function
insertionSort(numbers, size);
// Display the sorted array
cout << "Sorted array: ";
for (int i = 0; i < size; i++) {
cout << numbers[i] << " ";
}
cout << endl;
return 0; // End of program
}
Salida
Sorted array: 1 3 4 5 9
Comparte este ejercicio C++