Advertisement
tareqmahmud9

Muhit Bubble Sort

Feb 11th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #include <iostream>
  2. #include <time.h>
  3.  
  4. using namespace std;
  5.  
  6. void swap(int *xp, int *yp) {
  7.     int temp = *xp;
  8.     *xp = *yp;
  9.     *yp = temp;
  10. }
  11.  
  12. void bubbleSort(int arr[], int n) {
  13.     int i, j;
  14.     for (i = 0; i < n - 1; i++) {
  15.         for (j = 0; j < n - i - 1; j++) {
  16.             if (arr[j] > arr[j + 1]) {
  17.                 swap(&arr[j], &arr[j + 1]);
  18.             }
  19.         }
  20.     }
  21.  
  22.  
  23. }
  24.  
  25. int main() {
  26.     // Initialize variable
  27.     int c, size;
  28.     clock_t start, end;
  29.  
  30.     // Take or generate the input
  31.     cout << "how big do you want the array?" << endl;
  32.     cin >> size;
  33.  
  34.     int array[size];
  35.  
  36.     srand((unsigned) time(0));
  37.  
  38.     for (int i = 0; i < size; i++) {
  39.         array[i] = (rand() % 100) + 1;
  40.         cout << array[i] << " ";
  41.     }
  42.     cout << endl;
  43.  
  44.     // Sort that input with bubble sort and findout the time
  45.     start = clock();
  46.     bubbleSort(array, size);
  47.     end = clock();
  48.  
  49.     // Output the time
  50.     double duration_in_sec = ((double) (end - start)) / CLOCKS_PER_SEC;
  51.     cout << "Total time takes: " << duration_in_sec << "s" << endl;
  52.  
  53.     // Output the sorted element
  54.     cout << "Sorted list in ascending order: " << endl;
  55.  
  56.     for (c = 0; c <= size - 1; c++) {
  57.         cout << array[c] << " ";
  58.     }
  59.  
  60.     printf("\n");
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement