Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Activity Selection Problem: Algorithms [Code Snippet]

DZone's Guide to

Activity Selection Problem: Algorithms [Code Snippet]

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

· Big Data Zone ·
Free Resource

Hortonworks Sandbox for HDP and HDF is your chance to get started on learning, developing, testing and trying out new features. Each download comes preconfigured with interactive tutorials, sample data and developments from the Apache community.

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 Community Connection (HCC) is an online collaboration destination for developers, DevOps, customers and partners to get answers to questions, collaborate on technical articles and share code examples from GitHub.  Join the discussion.

Topics:
algorithms ,code snippet

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}