fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstdlib> // For rand()
  4. #include <ctime> // For clock()
  5. #include <omp.h> // For OpenMP
  6.  
  7. // Sequential Bubble Sort
  8. void bubbleSortSequential(int* arr, int size) {
  9. for (int i = 0; i < size - 1; i++) {
  10. for (int j = 0; j < size - i - 1; j++) {
  11. if (arr[j] > arr[j + 1]) {
  12. int temp = arr[j];
  13. arr[j] = arr[j + 1];
  14. arr[j + 1] = temp;
  15. }
  16. }
  17. }
  18. }
  19.  
  20. // Parallel Bubble Sort using OpenMP
  21. void bubbleSortParallel(int* arr, int size) {
  22. #pragma omp parallel for shared(arr, size)
  23. for (int i = 0; i < size - 1; i++) {
  24. for (int j = 0; j < size - i - 1; j++) {
  25. if (arr[j] > arr[j + 1]) {
  26. int temp = arr[j];
  27. arr[j] = arr[j + 1];
  28. arr[j + 1] = temp;
  29. }
  30. }
  31. }
  32. }
  33.  
  34. int main() {
  35. int size;
  36. std::cout << "Enter the size of the array: ";
  37. std::cin >> size;
  38.  
  39. int arr[size];
  40. std::cout << "Enter " << size << " integers:" << std::endl;
  41. for (int i = 0; i < size; i++) {
  42. std::cin >> arr[i];
  43. }
  44.  
  45. // Measure sequential bubble sort time
  46. clock_t startSeqBubble = clock();
  47. bubbleSortSequential(arr, size);
  48. clock_t endSeqBubble = clock();
  49. double timeSeqBubble = double(endSeqBubble - startSeqBubble) / CLOCKS_PER_SEC;
  50.  
  51. // Measure parallel bubble sort time
  52. int par_arr[size];
  53. std::copy(arr, arr + size, par_arr);
  54.  
  55. clock_t startParBubble = clock();
  56. bubbleSortParallel(par_arr, size);
  57. clock_t endParBubble = clock();
  58. double timeParBubble = double(endParBubble - startParBubble) / CLOCKS_PER_SEC;
  59.  
  60. // Print execution times
  61. std::cout << "Sequential Bubble Sort Time: " << timeSeqBubble << " seconds" << std::endl;
  62. std::cout << "Parallel Bubble Sort Time: " << timeParBubble << " seconds" << std::endl;
  63.  
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0.04s 5308KB
stdin
Standard input is empty
stdout
Enter the size of the array: Enter 5353 integers:
Sequential Bubble Sort Time: 0.016656 seconds
Parallel Bubble Sort Time: 0.012928 seconds