fork download
  1. #include <iostream>
  2. #include <omp.h>
  3. #include <chrono>
  4. #include <cstdlib>
  5.  
  6. using namespace std;
  7. using namespace chrono;
  8.  
  9. void bubbleSort(int arr[], int n)
  10. {
  11. for(int i=0;i<n-1;i++)
  12. for(int j=0;j<n-i-1;j++)
  13. if(arr[j] > arr[j+1])
  14. swap(arr[j], arr[j+1]);
  15. }
  16.  
  17. void parallelBubbleSort(int arr[], int n)
  18. {
  19. for(int i=0;i<n;i++)
  20. {
  21. if(i%2==0)
  22. {
  23. #pragma omp parallel for
  24. for(int j=0;j<n-1;j+=2)
  25. if(arr[j] > arr[j+1])
  26. swap(arr[j],arr[j+1]);
  27. }
  28. else
  29. {
  30. #pragma omp parallel for
  31. for(int j=1;j<n-1;j+=2)
  32. if(arr[j] > arr[j+1])
  33. swap(arr[j],arr[j+1]);
  34. }
  35. }
  36. }
  37.  
  38. int main()
  39. {
  40. int n = 1000;
  41. int arr1[n], arr2[n];
  42.  
  43. for(int i=0;i<n;i++)
  44. {
  45. int val = rand()%1000;
  46. arr1[i]=val;
  47. arr2[i]=val;
  48. }
  49.  
  50. auto start = high_resolution_clock::now();
  51. bubbleSort(arr1,n);
  52. auto end = high_resolution_clock::now();
  53. cout<<"Sequential Bubble Sort Time: "
  54. <<duration_cast<milliseconds>(end-start).count()<<" ms"<<endl;
  55.  
  56. start = high_resolution_clock::now();
  57. parallelBubbleSort(arr2,n);
  58. end = high_resolution_clock::now();
  59. cout<<"Parallel Bubble Sort Time: "
  60. <<duration_cast<milliseconds>(end-start).count()<<" ms"<<endl;
  61.  
  62. return 0;
  63. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Sequential Bubble Sort Time: 0 ms
Parallel Bubble Sort Time: 0 ms