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).