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

Effortlessly power IoT, predictive analytics, and machine learning applications with an elastic, resilient data infrastructure. Learn how with Mesosphere DC/OS.

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;
}


Learn to design and build better data-rich applications with this free eBook from O’Reilly. Brought to you by Mesosphere DC/OS.

Topics:
algorithms ,code snippet

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}