Advertisement
thinhhja2001

Untitled

Apr 4th, 2020
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. // 1 số mẫu test: => random 1 mảng 1 chiều có số lượng phần tử từ ít tới nhiều
  2. // 10 phần tử, 100 phần tử, 1,000, 10,000, 100,000 phần tử
  3.  
  4. #include <iostream>
  5. #include <stdlib.h>     /* srand, rand */
  6. #include <time.h>
  7. using namespace std;
  8. double ThuatToan1(int a[], int n,double &time_use) {
  9.     int maxSum = 0;
  10.     clock_t start, end;
  11.     start = clock();
  12.     for (int i = 0; i < n; i++)
  13.     {
  14.         for (int j = i; j < n; j++)
  15.         {
  16.             int thisSum = 0;
  17.             for (int k = i; k <= j; k++)
  18.                 thisSum += a[k];
  19.             if (thisSum > maxSum)
  20.                 maxSum = thisSum;
  21.         }
  22.     }
  23.     end = clock();
  24.  
  25.     time_use = (double)(end - start) / CLOCKS_PER_SEC;
  26.     return time_use;
  27. }
  28.  
  29. double ThuatToan2(int a[],int n,double &time_use)
  30. {
  31.     int maxSum = 0, thisSum = 0;
  32.     clock_t start, end;  
  33.     start = clock();
  34.     for (int j = 0; j < n; j++)
  35.     {
  36.         thisSum += a[j];
  37.         if (thisSum > maxSum)
  38.             maxSum = thisSum;
  39.         else if (thisSum < 0)
  40.             thisSum = 0;
  41.     }
  42.     end = clock();
  43.     time_use = (double)(end - start) / CLOCKS_PER_SEC;
  44.     return time_use;
  45. }
  46.  
  47. void RandomArray(int a[], int n) {
  48.     srand(time(NULL));
  49.     for (int i = 0;i<n;i++)
  50.         a[i] = rand() % 100000;
  51.  
  52. }
  53. int main()
  54. {
  55.     double time_use = 0;
  56.     int n;
  57.     cout << "nhap so luong phan tu ban muon \n";
  58.     cin >> n;
  59.     int a[100000];
  60.     RandomArray(a, n);
  61.     cout << "Thoi gian thuc hien thuat toan 1 la:\n";
  62.     cout << ThuatToan1(a, n, time_use) << "giay\n";
  63.     cout << "Thoi gian thuc hien thuat toan 2 la:\n";
  64.     cout << ThuatToan2(a, n, time_use) << "giay\n";
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement