Over a million developers have joined DZone.

Activity Selection Problem: Algorithms [Code Snippet]

Activity selection problem is a greedy algorithm, i.e always select the next optimal solution.

· Big Data Zone

Learn how you can maximize big data in the cloud with Apache Hadoop. Download this eBook now. Brought to you in partnership with Hortonworks.

Activity selection problem is a greedy algorithm, i.e always select the next optimal solution.

The greedy choice is to always pick the next activity whose finish time is least among the remaining activities and the start time is more than or equal to the finish time of previously selected activity. We can sort the activities according to their finishing time so that we always consider the next activity as minimum finishing time activity.

  1. Sort the activities according to their finishing time

  2. Select the first activity from the sorted array and print it.

  3. Do following for remaining activities in the sorted array.

If the start time of this activity is greater than the finish time of previously selected activity then select this activity and print it.

C Implementation:

#include<stdio.h>

voidprintMaxActivities(ints[], intf[], intn)
{
    inti, j;

    printf("Following activities are selected \n");

//first activity always gets selected


    i = 0;
    printf("%d ", i);
 //

    for(j = 1; j < n; j++)
    {
      // If this activity has start time greater than or
      // equal to the finish time of previously selected
      // activity, then select it
      if(s[j] >= f[i])
      {
          printf("%d ", j);
          i = j;
      }
    }
}

// driver program to test above function
intmain()
{
    ints[] =  {1, 3, 0, 5, 8, 5};
    intf[] =  {2, 4, 6, 7, 9, 9};
    intn = sizeof(s)/sizeof(s[0]);
    printMaxActivities(s, f, n);
    getchar();
    return0;
}


Hortonworks DataFlow is an integrated platform that makes data ingestion fast, easy, and secure. Download the white paper now.  Brought to you in partnership with Hortonworks

Topics:
algorithms ,code snippet

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}