Greedy Activity Selector C Source Code

The details of this problem can be find on my previous post : Greedy Activity Selector Java Source Code

First we must declare the function prototype

void recursiveActivitySelector(int*, int*, int, int, int*);
void greedyActivitySelector(int*, int*, int, int*);

Then here is the Recursive Solution of Greedy Activity Selector

void recursiveActivitySelector(int s[], int f[], int i, int j, int a[]){
     int m = i + 1;
     while (m < j && s[m] < f[i]){
           m = m + 1;
     }
     if (m < j){
           a[m] = 1;
           recursiveActivitySelector(s,f,m,j,a);
     }
}

And the Iterative Solution is

void greedyActivitySelector(int s[], int f[], int len, int a[]){
     int n = len;
     int i = 1;
     for (int m=1;m<n;m++){
         if (s[m] >= f[i]){
            a[m] = 1;
            i = m;
         }
     }
}

For testing the program, you can use main function like this

int main(){
    int a1[] = {1,0,0,0,0,0,0,0,0,0,0};
    int a2[] = {1,0,0,0,0,0,0,0,0,0,0};
    int s[] = {1,3,0,5,3,5,6,8,8,2,12};
    int f[] = {4,5,6,7,8,9,10,11,12,13,14};

    int len = sizeof(s) / sizeof(int);

    recursiveActivitySelector(s, f, 0, len, a1);
    printf("Recursive Solution : ");
    for (int i=0;i<len;i++){
        if (a1[i] == 1)
        printf("%d ",i+1);
    }

    printf("n");

    greedyActivitySelector(s, f, len, a2);
    printf("Iterative Solution : ");
    for (int i=0;i<len;i++){
        if (a2[i] == 1)
        printf("%d ",i+1);
    }

    getch();
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation