-2

I just started the Princeton Algorithms course and tried to implement a very basic quick find algorithm in C as follows -

#include <stdio.h>

void find(int *, int, int);
void unite(int *, int, int);

int main() {
    int arr[10], i, n1, n2, opt;
    char ch;

    for (i = 0; i < 10; i++)
        arr[i] = i;

    do {
        printf("1. Find\n2. Union\n");
        scanf("%d", &opt);
        if (opt == 1) {
            scanf("%d,%d", &n1, &n2);
            find(arr, n1, n2);
        }
        if (opt == 2) {
            scanf("%d,%d", &n1, &n2);
            unite(arr, n1, n2);
        }
        for (i = 0; i < 10; i++)
            printf("%d  ", arr[i]);
        printf("Continue? (Y/N)");
        getchar();
        scanf("%c", &ch);
    } while (ch == 'Y');
}

void find(int *id, int p, int q) {
    if ((*(id + p)) == (*(id + q)))
        printf("Connected\n");
}

void unite(int *id, int p, int q) {
    int i;
    for (i = 0; i < 10; i++) {
        if ((*(id + i)) == (*(id + p)))
            *(id + i) = *(id + q);
    }
}

The program isn't running as it is supposed to. When I try to do a union(4,3) and then a union(3,8), only arr[3] changes its value and not arr[4]. Also, I'm not sure why I had to use getchar (the program kept ending without it).

chqrlie
  • 131,814
  • 10
  • 121
  • 189

1 Answers1

0

This line:

if((*(id+i))==(*(id+p)))

is equivalent to:

if (id[i] == id[p])

and tests the current id for i with the current id for p.

The problem is that id[p] may have already been changed to id[q]!

So when you try to turn all 3's into 8's, after we change arr[3] to 8, from then on we are only changing 8's into 8's.

Instead try storing the current id for p, and testing against that:

void unite(int *id, int p, int q)
{
    int i;
    int id_to_change = id[p];
    for(i=0;i<10;i++)
    {
        if(id[i] == id_to_change)
            id[i] = id[q];
    }
}
Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75