Final answer:
This program generates a random array of integers, sorts it using the bubble sort algorithm, and displays the sorted array along with the elapsed time. It uses the rand function to generate random integers and the time function to measure the elapsed time. The bubble sort algorithm swaps adjacent numbers until the array is sorted in ascending order.
Step-by-step explanation:
To write a C program that generates random integers, stores them in an array, sorts the array using the bubble sort algorithm, and displays the sorted array along with the elapsed time, you can use the following code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
int main() {
int n, i;
printf("Enter the number of integers: ");
scanf("%d", &n);
int arr[n];
srand(time(0));
for (i = 0; i < n; i++)
arr[i] = rand() % 2001 - 1000;
clock_t start = clock();
bubbleSort(arr, n);
clock_t end = clock();
double time_spent = (double)(end - start) / CLOCKS_PER_SEC;
printf("Sorted Array: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("
Elapsed Time: %.3f seconds
", time_spent);
return 0;
}
This program uses the rand function from the stdlib.h library to generate random integers in the range of -1000 to 1000. The time function from the time.h library is used to seed the random number generator. The bubble sort algorithm is implemented in the function bubbleSort, which swaps adjacent numbers until the array is sorted in ascending order. The elapsed time is calculated using the difference between the start and end clock ticks divided by the CLOCKS_PER_SEC constant. Finally, the sorted array and the elapsed time are displayed.