I ve to sort an array according to finish time and accordingly start time should be arranged, how can we do this using predefined function qsort. Both Start time and finish time, i ve considered it be in a structure ,
.here is the code..

#include<stdio.h>
#include<stdlib.h>
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
struct time {
int start[100005];
int finish[100005];
}t;
int main() {
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d%d",&t.start[i],&t.finish[i]);
qsort(t.finish,n,sizeof(int),compare);
for(i=0;i<n;i++)
printf("%d %d\n",t.start[i],t.finish[i]);
return 0;
}

2
Contributors
2
Replies
5
Views
5 Years
Discussion Span
Last Post by cse.avinash

I'm not sure I understand the requirement. It looks like start and finish are related, in which case sorting by finish time would be more meaningful like this:

#include <stdio.h>
#include <stdlib.h>

struct ElapsedTime
{
int start, finish;
};

int compare_elapsed(void const* a, void const* b)
{
struct ElapsedTime const* pa = a;
struct ElapsedTime const* pb = b;

return pa->finish - pb->finish;
}

int main(void)
{
struct ElapsedTime times[] =
{
{1, 5},
{5, 11},
{3, 4},
{1, 2},
{5, 9},
};
int n = sizeof times / sizeof *times;

qsort(times, n, sizeof(times[0]), compare_elapsed);

for (int i = 0; i < n; ++i)
{
printf("%d, %d\n", times[i].start, times[i].finish);
}

return 0;
}


The difference being that it's an array of structs where each struct has only a single pair of times, then the array is sorted according to the finish time. This design strikes me as more reasonable, but I am making an assumption based on experience rather than what your actual requirements are.

Thank You Sir :)