2
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define LIMIT 30000

void CreateArray(int *p, int N) {
    int i;
    p = (int *)malloc(N * sizeof(int));
    srand((long)210);
    for (i = 0; i < N; i++)
        *(p + i) = rand() % LIMIT;

    for (i = 0; i < N; i++)
        printf("%d ", p[i]);
}

void Search(int *p, int N, int key) {
    int comparisons = 0, success_search = 0;
    int i;

    clock_t start, end;
    double elapsed;
    start = clock();

    for (i = 0; i < N; i++) {
        if (key == p[i]) {
            comparisons++;
            success_search++;
            printf("\nFound!");
            break;
        } else {
            comparisons++;
            printf("\nNot found!");
        }
    }

    end = clock();
    elapsed = ((double)(end - start)) / CLOCKS_PER_SEC;

    printf("\nTotal comparisons: %d \n", comparisons);
    printf("Time elapsed: %f \n", elapsed);
    printf("Successful comparisons: %d \n\n", success_search);
}

int main() {
    int N, i, p, key;

    key = 1;
    CreateArray(&p, N = 7);
    Search(&p, N, key);
}

I'm trying to create a pseudo-random array and then try to search for a specific number in it and keep track of the total comparisons made and the total time needed to complete the search. I have manually inserted a number that is not in the array and it keeps saying that the number was found after 3 comparisons. Also the time elapsed always appears to be zero. I can't figure out what's wrong.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
user3120283
  • 85
  • 2
  • 9
  • 1
    `int *p;` => `CreateArray(&p, N = 7);` => `void CreateArray (int **p, int N)` => `*p = (int*) malloc (N*sizeof(int));` – BLUEPIXY Oct 21 '16 at 19:35
  • "the time elapsed always appears to be zero" perhaps because of the granularity of the timer. For example Windows MSVC has `#define CLOCKS_PER_SEC ((clock_t)1000)` – Weather Vane Oct 21 '16 at 19:41
  • @BLUEPIXY If i do the changes you recommend, the program won't even start. I get program stopped working error. – user3120283 Oct 21 '16 at 19:43
  • [DEMO](http://ideone.com/mAQrQm) – BLUEPIXY Oct 21 '16 at 19:48
  • @BLUEPIXY is right, but the argument to CreateArray() must be a pointer to a pointer, not a pointer to a stack variable. – Bjorn A. Oct 21 '16 at 20:01
  • You should improve the debug printing and get the operation of the code correct before you bother worrying about the time. A linear search of an array of 7 elements is barely going to take microseconds on a modern computer, but the resolution of `clock` is typically in the range 1-20 milliseconds. – Jonathan Leffler Oct 21 '16 at 20:06
  • @BLUEPIXY You're right, it's working. Hmm, what if i want to do the search e.g 1000 times with a different number to find each time, how can i get the total number of comparisons, total time for searching and total number of successful searches? I have to return the 3 variables from the Search function to main? How can i return 3 variables with 1 function? – user3120283 Oct 21 '16 at 20:17
  • @user3120283 1) return struct. 2) pointer argument. – BLUEPIXY Oct 22 '16 at 11:25
  • @BLUEPIXY I don't want struct, so i tried it the other way but something is wrong with my counters and i can't figure out what i did wrong. Here's a [demo](http://ideone.com/c1mrUk) where i try to run the search 100 times, each time with a different key. I want to get the total number of comparisons made, the successful searches and the total search time in these 100 times. I appreciate all your help – user3120283 Oct 22 '16 at 13:57
  • @user3120283 `(*comparisons++)` --> `(*comparisons)++` or `++*comparisons`, and Need initialize e.g. `comparisons=0, total_comparisons=0` and `comparisons` and `success_search` reset to `0` before call (or at first of inside of function). – BLUEPIXY Oct 22 '16 at 14:06
  • @BLUEPIXY I managed to fix the comparisons and success_search counters. But time elapsed is still not working. Even with e.g N = 5000 i get time elapsed = 0 (i'm using codeblocks). [here](http://ideone.com/c1mrUk) – user3120283 Oct 22 '16 at 14:40
  • try Use `%g` instead of `%f`. Since the value is very small. Also `total_elapsed` isn't initialized. – BLUEPIXY Oct 22 '16 at 15:03
  • @BLUEPIXY So eventually i'm trying to do [this](http://ideone.com/c1mrUk). It seems that when N is low like e.g 5000 i get almost every time 0 successful searches and when N is high (like over 60000) i always get 100% success. The results seem weird to me. Are they normal? – user3120283 Oct 22 '16 at 15:18
  • try `srand(time(NULL));` befor for-loop at **main**. (Delete `srand` in `CreateArray`) – BLUEPIXY Oct 22 '16 at 15:30
  • @BLUEPIXY Thank you so much for this!! It finally works as it should. You sir, deserve a cookie! Thank you! – user3120283 Oct 22 '16 at 15:34

2 Answers2

0

Make the following changes.

1) You need to allocate array and pass it to different functions. So "n" should be a pointer.

int *n = NULL;

2) You want CreateArray() to allocate memory and pass the pointer.

void CreateArray (int **p, int N)

3) You have to pass pointer to Search(). So call from main() becomes

Search(p, N, key);

I think it should work fine as expected now.

For time elapsed, you refer to Weather Vane's comment in your question.

MayurK
  • 1,925
  • 14
  • 27
0

There are multiple problems in your code:

  • CreateArray should return the pointer to the allocated space. Passing it a pointer to a local int in main() makes no sense.

  • you should test for malloc potential failure.

  • Search should get the pointer to the allocated array, not the address of a local int.

  • Search should print the Not found message just once at the end of the scan phase.

  • If you want to count the number of successful comparisons, you should not break from the loop when you find the first one, but then the total number of comparisons is N.

  • for better timing accuracy, you should avoid using printf inside the timed fragment.

  • you should free the memory before exiting the program.

Here is a corrected version:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define LIMIT 30000

void CreateArray(int N) {
    int i;
    int *p = (int *)malloc(N * sizeof(int));
    if (p != NULL) {
        srand((long)210);
        for (i = 0; i < N; i++)
            *(p + i) = rand() % LIMIT;

        for (i = 0; i < N; i++)
            printf("%d ", p[i]);
    }
    return p;
}

void Search(int *p, int N, int key) {
    int comparisons = 0, success_search = 0;
    int i;

    clock_t start, end;
    double elapsed;
    start = clock();

    for (i = 0; i < N; i++) {
        comparisons++;
        if (key == p[i])
            success_search++;
    }
    end = clock();
    elapsed = ((double)(end - start)) / CLOCKS_PER_SEC;

    if (success_search)
        printf("Found!\n");
    else
        printf("Not found!\n");

    printf("Total comparisons: %d\n", comparisons);
    printf("Successful comparisons: %d\n\n", success_search);
    printf("Time elapsed: %f\n", elapsed);
}

int main() {
    int N, i, key;
    int *p;

    key = 1;
    N = 7;
    p = CreateArray(N);
    if (p == NULL) {
        fprintf(stderr, "cannot allocate memory for %d elements\n", N);
        return 1;
    }
    Search(p, N, key);
    free(p);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189