C code for bubble sort

 avatar
unknown
c_cpp
5 months ago
2.0 kB
11
Indexable
#include <stdio.h>

/*
 * Main function to perform Bubble Sort on an array.
 * 
 * Bubble Sort works by repeatedly swapping adjacent elements if they are in the wrong order.
 * 
 * This program allows sorting the array in:
 *  - Ascending Order: Smallest to largest (default behavior).
 *  - Descending Order: Largest to smallest (requires a simple modification).
 *
 * Steps:
 * 1. Define an array of integers.
 * 2. Use nested loops to compare adjacent elements.
 * 3. Swap elements based on the chosen order:
 *    - Ascending: Swap if the current element is greater than the next.
 *    - Descending: Swap if the current element is smaller than the next.
 * 4. Display the sorted array.
 *
 * Returns:
 * - 0 on successful execution.
 */
int main() {
    // Define an array of integers to sort
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    
    // Calculate the size of the array
    int size = sizeof(arr) / sizeof(arr[0]);

    // Variables for iteration and swapping
    int i, j, temp;

    // Bubble Sort algorithm (default: ascending order)
    for (i = 0; i < size - 1; i++) {
        for (j = 0; j < size - i - 1; j++) {
            /*
             * For Ascending Order:
             * Use the condition: arr[j] > arr[j + 1]
             * This swaps elements to ensure smaller values move to the front.
             *
             * For Descending Order:
             * Modify the condition to: arr[j] < arr[j + 1]
             * This swaps elements to ensure larger values move to the front.
             */
            if (arr[j] > arr[j + 1]) { // Change to arr[j] < arr[j + 1] for descending order
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

    // Print the sorted array
    printf("Sorted array: ");
    for (i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    // Return 0 to indicate successful execution
    return 0;
}
Editor is loading...
Leave a Comment