Loading…
DAA · Greedy · Program 16 · In the record
Write a program in c to solve the job sequencing with deadlines problem using the greedy method and find its execution time using the time function.
Algorithm: JobSequencing(p, d, n) 1. Start 2. maxd <- largest deadline 3. For t <- 1 to maxd do 4. slot[t] <- 0 5. Sort the jobs in decreasing order of profit p[i] (merge sort) 6. total <- 0 7. For each job i in sorted order do 8. For t <- d[i] down to 1 do 9. if slot[t] == 0 then 10. slot[t] <- i 11. total <- total + p[i] 12. break 13. print the jobs in slot[1..maxd] and total 14. Stop
1#include<stdio.h>2#include<time.h>3 4int p[50];5int count=0;6 7void merge(int a[],int low,int mid,int high) {8 int n1=mid-low+1,n2=high-mid;9 int left[n1],right[n2];10 int i,j,k;11 12 for(i=0;i<n1;i++)13 left[i]=a[low+i];14 for(j=0;j<n2;j++)15 right[j]=a[mid+1+j];16 17 i=0;18 j=0;19 k=low;20 while(i<n1 && j<n2) {21 count++;22 if(p[left[i]]>=p[right[j]])23 a[k++]=left[i++];24 else25 a[k++]=right[j++];26 }27 while(i<n1)28 a[k++]=left[i++];29 while(j<n2)30 a[k++]=right[j++];31}32 33void mergeSort(int a[],int low,int high) {34 if(low<high) {35 int mid=(low+high)/2;36 mergeSort(a,low,mid);37 mergeSort(a,mid+1,high);38 merge(a,low,mid,high);39 }40}41 42int main() {43 int n,i,k,t,maxd=0,total=0;44 printf("Enter the number of jobs:");45 scanf("%d",&n);46 int d[n+1],order[n];47 printf("Enter the profits of %d jobs:",n);48 for(i=1;i<=n;i++)49 scanf("%d",&p[i]);50 printf("Enter the deadlines of %d jobs:",n);51 for(i=1;i<=n;i++) {52 scanf("%d",&d[i]);53 if(d[i]>maxd)54 maxd=d[i];55 }56 int slot[maxd+1];57 58 clock_t start=clock();59 for(i=1;i<=n;i++)60 order[i-1]=i;61 for(t=1;t<=maxd;t++)62 slot[t]=0;63 mergeSort(order,0,n-1);64 for(k=0;k<n;k++) {65 i=order[k];66 for(t=d[i];t>=1;t--) {67 count++;68 if(slot[t]==0) {69 slot[t]=i;70 total=total+p[i];71 break;72 }73 }74 }75 clock_t end=clock();76 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;77 78 printf("\nJobs in decreasing order of profit:\nJob\tProfit\tDeadline");79 for(k=0;k<n;k++) {80 i=order[k];81 printf("\nJ%d\t%d\t%d",i,p[i],d[i]);82 }83 printf("\nJob sequence:");84 for(t=1;t<=maxd;t++)85 if(slot[t]!=0)86 printf("\tJ%d",slot[t]);87 printf("\nMaximum profit:%d",total);88 printf("\nNumber of comparisons:%d",count);89 printf("\nTime taken:%f seconds",time_taken);90 printf("\nTime complexity: O(n^2)");91 printf("\nSpace complexity: O(n)");92 printf("\n");93 return 0;94}5 ⏎ 100 19 27 25 15 ⏎ 2 1 2 1 3Enter the number of jobs:5 Enter the profits of 5 jobs:100 19 27 25 15 Enter the deadlines of 5 jobs:2 1 2 1 3 Jobs in decreasing order of profit: Job Profit Deadline J1 100 2 J3 27 2 J4 25 1 J2 19 1 J5 15 3 Job sequence: J3 J1 J5 Maximum profit:142 Number of comparisons:14 Time taken:0.000003 seconds Time complexity: O(n^2) Space complexity: O(n)
Run program 16 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.