Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-05-13· OpenAIAi2 WildChat-4.8M (AI2)

Generate a C program of bubble sort

  1. User

    Generate a C program of bubble sort

  2. 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:

    1. Main Function:

      • It initializes an example array and calculates its size.
      • It prints the unsorted array.
      • It calls the bubbleSort function to sort the array.
      • It prints the sorted array.
    2. bubbleSort Function:

      • It takes an array arr and its size n as arguments.
      • It uses two nested loops. The outer loop goes from 0 to n-1 and the inner loop goes from 0 to n-i-1.
      • If an element at index j is greater than the element at index j+1, it swaps the two elements.
    3. 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.c
    

    Then, you can run the compiled program:

    ./bubble_sort
    

    This will output the unsorted and sorted array to the console.