How to measure bubble sort with an array of 30,000 random integers in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// ------------------------------------------------------------
// Function: generateRandomArray
// Purpose:  Fill an array with random integers
// ------------------------------------------------------------
void generateRandomArray(int* arr, int size) {
    for (int i = 0; i < size; i++) {
        arr[i] = rand();   // Random integer
    }
}

// ------------------------------------------------------------
// Function: bubbleSort
// Purpose:  Perform bubble sort on the array
// Notes:    Bubble sort is O(n^2) and extremely slow for large n
// ------------------------------------------------------------
void bubbleSort(int* arr, int size) {
    int n = size;
    int swapped;

    for (int i = 0; i < n - 1; i++) {
        swapped = 0;

        // Compare each pair
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap elements
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;

                swapped = 1;
            }
        }

        // Optimization: stop if no swaps occurred
        if (!swapped) {
            break;
        }
    }
}

// ------------------------------------------------------------
// Function: measureBubbleSort
// Purpose:  Measure how long bubble sort takes
// ------------------------------------------------------------
void measureBubbleSort(int size) {
    int* arr = (int*)malloc(size * sizeof(int));
    if (!arr) {
        printf("Memory allocation failed.\n");
        return;
    }

    printf("Generating array of %d random integers...\n", size);
    generateRandomArray(arr, size);

    printf("Starting bubble sort...\n");

    // Start timer
    clock_t start = clock();

    bubbleSort(arr, size);

    // End timer
    clock_t end = clock();

    // Calculate duration in seconds
    double duration = (double)(end - start) / CLOCKS_PER_SEC;

    printf("Bubble sort completed.\n");
    printf("Time taken: %.6f seconds\n", duration);

    free(arr);
}

// ------------------------------------------------------------
// Main function
// ------------------------------------------------------------
int main() {
    const int SIZE = 30000;  // 20,000 integers

    measureBubbleSort(SIZE);

    return 0;
}


/*
run:

Generating array of 30000 random integers...
Starting bubble sort...
Bubble sort completed.
Time taken: 1.459563 seconds

*/

 



answered Jul 2 by avibootz
...