Implementa el algoritmo bubble sort en C.
- User
Implementa el algoritmo
bubble sorten C. - Assistant
Aquí te presento una implementación del algoritmo "bubble sort" en C: #include <stdio.h>
void bubbleSort(int arr[], int n) { int i, j; for (i = 0; i < n-1; i++) { for (j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }
int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr)/sizeof(arr[0]); printf("Array original: \n"); for (int i=0; i < n; i++) printf("%d ", arr[i]); printf("\n");
bubbleSort(arr, n);
printf("Array ordenado: \n"); for (int i=0; i < n; i++) printf("%d ", arr[i]); printf("\n"); return 0; }
Este algoritmo recibe un arreglo de enteros y su tamaño, y los ordena de menor a mayor utilizando el método de "bubble sort".
El algoritmo funciona comparando cada elemento consecutivo en el arreglo y intercambiándolos si están en el orden incorrecto. Este proceso se repite hasta que todos los elementos estén en el orden correcto.
La eficiencia del algoritmo "bubble sort" es O(n^2), por lo que puede ser ineficiente para arreglos grandes. Sin embargo, es un algoritmo sencillo de entender y implementar.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.