Implementa el algoritmo bubble sort en C.
- User
Implementa el algoritmo
bubble sorten C. - Assistant
#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 antes del ordenamiento:\n"); int i; for (i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n");
bubbleSort(arr, n);
printf("Array después del ordenamiento:\n"); for (i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n");
return 0; }
El código utiliza dos bucles for anidados para comparar cada par de elementos consecutivos en el arreglo y, si el primer elemento es mayor que el segundo, los intercambia. Este proceso se repite hasta que el arreglo esté ordenado de menor a mayor.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.