mardi 28 janvier 2020

All the values in aray are zero

I am trying to find the time taken by a linear search program to find the time taken by a function to find a random key to from a random array, the problem is that the array comes out to be entirely 0

#include <chrono>
#include <cstdlib>
#include <iostream>
#include <random>

using namespace std;
using namespace std::chrono;

int linearsearch(int a[], int key, int i) {
  int count = 0;
  for (int j = 1; j <= i; j++) {
    if (key == a[i]) {
      count++;
    }
  }
  cout << "\nelement occured exactly " << count << " times";
  return 0;
}

int main() {
  int i, j, l;
  srand(time(0));
  for (i = 5000; i < 50000;) {
    int a[i];
    for (j = 0; j < 100; j++) {  // loop for test case, 100
      a[i] = rand() % i;
      int key = rand() % i;
      auto start = high_resolution_clock::now();
      linearsearch(a, key, i);
      auto stop = high_resolution_clock::now();
      auto duration = duration_cast<microseconds>(stop - start);
      cout << "\narray is ";
      for (l = 0; l < a[i]; l++) cout << a[l] << " ";
      cout << "\nand key is " << key;
      cout << "\nTime taken by function: " << duration.count()
           << " microseconds" << endl;
    }
    i = i + 5000;
  }
  return 0;
}



Aucun commentaire:

Enregistrer un commentaire