SHARE
TWEET

Untitled

a guest Apr 26th, 2019 47 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <time.h>
  4. #include <chrono>
  5. using namespace std;
  6. void selection_sort(int arr[], int n)
  7. {
  8.     int j = 0;
  9.     for(int i = 0; i < n; i++){
  10.         j = i;
  11.         for(int k = i; k < n; k++)
  12.             if (arr[j] > arr[k])
  13.                 j = k;
  14.         swap(arr[i],arr[j]);
  15.     }
  16. }
  17.  
  18. void bubble_sort(int arr[], int n){
  19.     for(int i = 0; i < n; i++)
  20.         for(int j = n - 1; j >= i + 1; j--)
  21.             if(arr[j] < arr[j-1])
  22.                 swap(arr[j],arr[j - 1]);
  23. }
  24. void insert_sort(int arr[], int n){
  25.     for (int i = 1; i < n; i++){
  26.         int j = i;
  27.         while (j > 0 or arr[j] < arr[j - 1])
  28.         {
  29.             swap(arr[j],arr[j - 1]);
  30.             j--;
  31.         }
  32.     }
  33. }
  34. int main() {
  35.     int n;
  36.     cin >> n;
  37.     int arr[n], arr2[n], arr3[n], arr4[n];
  38.     srand(time(0));
  39.     for (int i = 0; i < n; i++){
  40.         arr[i] = rand() % 100001;
  41.         arr2[i] = arr[i];
  42.         arr3[i] = arr[i];
  43.         arr4[i] = arr[i];
  44.     }
  45.    
  46.     auto begin = std::chrono::steady_clock::now();
  47.    
  48.     bubble_sort(arr, n);
  49.    
  50.     auto end = std::chrono::steady_clock::now();
  51.    
  52.     auto elapsed_ms = chrono::duration_cast<std::chrono::milliseconds>(end - begin);
  53.    
  54.     cout << "The time of bubble_sort: " << elapsed_ms.count() << " ms\n";
  55.    
  56.     begin = std::chrono::steady_clock::now();
  57.    
  58.     insert_sort(arr2, n);
  59.    
  60.     end = std::chrono::steady_clock::now();
  61.    
  62.     elapsed_ms = chrono::duration_cast<std::chrono::milliseconds>(end - begin);
  63.    
  64.     cout << "The time of insert_sort: " << elapsed_ms.count() << " ms\n";
  65.    
  66.     begin = std::chrono::steady_clock::now();
  67.    
  68.     selection_sort(arr3, n);
  69.    
  70.     end = std::chrono::steady_clock::now();
  71.    
  72.     elapsed_ms = chrono::duration_cast<std::chrono::milliseconds>(end - begin);
  73.    
  74.     cout << "The time of selection_sort: " << elapsed_ms.count() << " ms\n";
  75.     return 0;
  76. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top