gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
Generate a C program of bubble sort
- User
Generate a C program of bubble sort
- Assistant
Sure, here is a simple C program that demonstrates the Bubble Sort algorithm:
#include <stdio.h> // Function prototypes void bubbleSort(int arr[], int n); void printArray(int arr[], int size); int main() { // Example array int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr)/sizeof(arr[0]); printf("Unsorted array: \n"); printArray(arr, n); bubbleSort(arr, n); printf("Sorted array: \n"); printArray(arr, n); return 0; } // Function to perform bubble sort on an array void bubbleSort(int arr[], int n) { for (int i = 0; i < n-1; i++) { for (int j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { // Swap arr[j] and arr[j+1] int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } // Function to print an array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); }Explanation:
-
Main Function:
- It initializes an example array and calculates its size.
- It prints the unsorted array.
- It calls the
bubbleSortfunction to sort the array. - It prints the sorted array.
-
bubbleSort Function:
- It takes an array
arrand its sizenas arguments. - It uses two nested loops. The outer loop goes from 0 to
n-1and the inner loop goes from 0 ton-i-1. - If an element at index
jis greater than the element at indexj+1, it swaps the two elements.
- It takes an array
-
printArray Function:
- It takes an array and its size as arguments and prints the elements of the array.
Compile the program using a C compiler, for example
gcc:gcc -o bubble_sort bubble_sort.cThen, you can run the compiled program:
./bubble_sortThis will output the unsorted and sorted array to the console.
-