SYBCom(CA) DS Practical Slip 11 Q.A

Write a C program to accept and sort n elements in ascending order by using bubble sort and also count the number of swaps. Display the sorted list and total no of swap count.

#include <stdio.h>

int main() {
    int n, i, j, temp, swapCount = 0;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    int arr[n];

    // Accept elements
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Bubble Sort with swap count
    for(i = 0; i < n - 1; i++) {
        for(j = 0; j < n - i - 1; j++) {
            if(arr[j] > arr[j + 1]) {
                // Swap
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapCount++;
            }
        }
    }

    // Display sorted array
    printf("Sorted array in ascending order:\n");
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    // Display total number of swaps
    printf("Total number of swaps: %d\n", swapCount);

    return 0;
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top