Skip to content

Instantly share code, notes, and snippets.

@ritwickdey
Created November 28, 2017 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ritwickdey/42e9b05bbbdc80213a6246b2a6fbaf8c to your computer and use it in GitHub Desktop.
Save ritwickdey/42e9b05bbbdc80213a6246b2a6fbaf8c to your computer and use it in GitHub Desktop.
JobScheduling Algorithm (Greedy Approach) implemented with C
#include <stdio.h>
#include <stdlib.h>
typedef struct job
{
int id;
int deadLine;
float profit;
int isPossible;
} job;
void margeRev(job *arr, int low, int mid, int high)
{
int i = low;
int j = mid + 1;
int c = 0;
int temp_Arr_size = high - low + 1;
job *tempArr = (job *)malloc(sizeof(arr[0]) * temp_Arr_size);
while (i <= mid && j <= high)
if (arr[i].profit > arr[j].profit)
tempArr[c++] = arr[i++];
else
tempArr[c++] = arr[j++];
while (i <= mid)
tempArr[c++] = arr[i++];
while (j <= high)
tempArr[c++] = arr[j++];
for (i = low, c = 0; i <= high; i++)
arr[i] = tempArr[c++];
}
void margeSortRev(job *arr, int low, int high)
{
if (low < high)
{
int mid = (high + low) / 2;
margeSortRev(arr, low, mid);
margeSortRev(arr, mid + 1, high);
margeRev(arr, low, mid, high);
}
}
int getMaxDeadline(job *jobs, int n)
{
int i = 0;
int maxDeadline = -1;
for (i = 0; i < n; i++)
{
if (maxDeadline < jobs[i].deadLine)
maxDeadline = jobs[i].deadLine;
}
return maxDeadline;
}
int getSlotIndexIfTaskIsPossible(job jobElem, int *slot)
{
int i = jobElem.deadLine - 1;
while (i >= 0)
{
if (slot[i] == 0)
return i;
i--;
}
return -1;
}
float job_schedule(job *jobs, int n)
{
float profit = 0;
int i = 0;
int *slot = (int *)calloc(sizeof(int), getMaxDeadline(jobs, n));
margeSortRev(jobs, 0, n - 1);
for (i = 0; i < n; i++)
{
jobs[i].isPossible = 0;
int slotIndex = getSlotIndexIfTaskIsPossible(jobs[i], slot);
if (slotIndex != -1)
{
slot[slotIndex] = 1;
profit += jobs[i].profit;
jobs[i].isPossible = 1;
}
}
return profit;
}
int main()
{
int n, i;
printf("How many Jobs? ");
scanf("%d", &n);
job *jobs = (job *)malloc(n * sizeof(job));
for (i = 0; i < n; i++)
{
printf("%d. Enter Job Id, deadLine, profit : ", i + 1);
scanf("%d %d %f", &jobs[i].id, &jobs[i].deadLine, &jobs[i].profit);
}
float profit = job_schedule(jobs, n);
printf("\n----------\n");
printf("Id \t Profit \t Dead-Line \tIs Possible\n");
for (i = 0; i < n; i++)
{
printf("%d \t %0.1f \t\t %d \t\t %s\n", jobs[i].id, jobs[i].profit, jobs[i].deadLine, jobs[i].isPossible ? "Yes" : "No");
}
printf("\n----------\n");
printf("\nTotal Profit = %0.2f\n", profit);
printf("\n----------\n");
/*
Sample:
Input:
6
1, 2, 100
2, 1, 120
3, 3, 140
4, 2, 60
5, 4, 110
6, 4, 5
output:
470
};
*/
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment