Untitled

mail@pastecode.io avatar
unknown
plain_text
14 days ago
1.1 kB
2
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

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;
            }
        }
    }
}

int main() {
    int n = 10000; // Size of array
    int arr[n];

    // Initialize array with random values
    srand(time(NULL));
    for (int i = 0; i < n; i++) {
        arr[i] = rand() % 1000;
    }

    // Calculate time taken for sorting
    clock_t start_time = clock();
    bubbleSort(arr, n);
    clock_t end_time = clock();

    // Calculate time taken in milliseconds
    double time_taken = ((double) (end_time - start_time)) / CLOCKS_PER_SEC * 1000;

    // Print sorted array and time taken
    printf("Sorted array:\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\nTime taken: %f milliseconds\n", time_taken);

    return 0;
}
Leave a Comment