Sunday, October 18, 2015

C Program to sort the processes according to their priority

/* =====================================================================================
 * *
 * *       Filename:  procPri.c
 * *        Created:  Tuesday 20 January 2015 17:30:17  IST
 * *       Compiler:  gcc
 * *         Author:  Manoj Kumar Patra,manojpatra.sit@gmail.com
 * *   Organization:  SCIS,University of Hyderabad
 * *
 * * =====================================================================================*/

#include <stdio.h>
#include <stdlib.h>
typedef int (*compfn)(const void*, const void*);
struct process
{
int  priority;
char name[15];
};
struct process array[10]  = { {  1, "Process1"    },
{  5, "Process2" },
{  8, "Process3" },
{  4, "Process4" },
{  3, "Process5" },
{  9, "Process6" },
{  2, "Process7" },
{  6, "Process8" },
{ 10, "Process9" },
{  7, "Process10"}  };

void printarray(void);
int  compare(struct process *, struct process *);
void main(void)
{
printf("List of Processes before sorting:\n");
printarray();

qsort((void *) &array,              // Beginning address of array
10,                         // Number of elements in array
sizeof(struct process),     // Size of each element
(compfn)compare );          // Pointer to compare function

printf("\nList Processes after sorting:\n");
printarray();
}

int compare(struct process *elem1, struct process *elem2)
{
if ( elem1->priority < elem2->priority)
return -1;

else if (elem1->priority > elem2->priority)
return 1;

else
return 0;
}

void printarray(void)
{
int i;
printf("PRI\tPname\n");
printf("----\t-----\n");
for (i = 0; i < 10; i++)
printf("%d\t%s\n",array[i].priority, array[i].name);
}

No comments:

Post a Comment