I need to use mergesort to sort the data in a file that has the names and ages of 10 different people , first i have to sort the names in ascending ascii order and then i have to sort them by their age but im not sure how to do it this is what i have so far
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define NUMBER_OFPEOPLE 10
typedef struct{
char name[6] ;
int age ;
}people ;
typedef char byte ;
void memcopy( byte *to, byte *from, int count ) {
while (count-- > 0 )
*to++ = *from++ ;
}
int compare_age( byte *a , byte *b ) {
int aa ;
int bb ;
aa = ((people *)a)->age ;
bb = ((people *)b)->age ;
if (aa < bb) return 1 ;
if (aa > bb) return -1 ;
return 0 ;
}
int compare_name( byte *a , byte *b ) {
char aa[6] ;
char bb[6] ;
strcpy(aa, ((people *)a)->name) ;
strcpy(bb, ((people *)b)->name) ;
return strcmp(aa, bb) ;
}
void merge_sort(byte data[], int n , int elementsize , int (*p_cmp_f)() ) ;
int main(void){
int j, n = 10 , i;
people *A ;
people s ;
A=(people *)malloc(sizeof(people)*n) ;
if ( A == NULL ) { printf(" Error mallocing \n" ); return -1 ; }
FILE *fp ;
fp = fopen("people","r") ;
for(j = 0 ; j < 10 ; j++){
fscanf(fp, "%s %d\n",&s.name,&s.age);
}
merge_sort( (byte *) A, n , sizeof(people) , compare_name ) ;
for(j = 0 ; j < 10 ; j++ ) printf("%s" "%d" , s.name,s.age) ;
merge_sort( (byte *) A, n , sizeof(people) , compare_age ) ;
for(i = 0 ; i < 10 ; i++ ) printf("%d" "%s" , s.age,s.name) ;
return 0 ;
}
void merge_sort( byte data[], int n, int elementsize, int (*p_cmp_f)( ) ) {
byte *firsthalf ;
byte *endoffirsthalf ;
byte *secondhalf ;
byte *endofsecondhalf ;
byte *resultbuffer , *p_result ;
int halfsize ;
if(n <= 1)
return ;
halfsize = n/2 ;
firsthalf = data ;
secondhalf = data + halfsize * elementsize ;
merge_sort(firsthalf ,halfsize,elementsize, p_cmp_f) ;
merge_sort(secondhalf,n-halfsize,elementsize,p_cmp_f) ;
endoffirsthalf = secondhalf ;
endofsecondhalf = data + n * elementsize ;
resultbuffer = (byte *) malloc(n * elementsize);
p_result = resultbuffer ;
while(firsthalf < endoffirsthalf && secondhalf < endofsecondhalf ){
if((*p_cmp_f)(firsthalf,secondhalf) < 0) {
memcopy(p_result , firsthalf , elementsize) ;
firsthalf += elementsize ;
} else{
memcopy(p_result , secondhalf , elementsize);
secondhalf += elementsize ;
}
p_result += elementsize ;
}
while(firsthalf < endoffirsthalf){
memcopy(p_result,firsthalf,elementsize) ;
firsthalf += elementsize ;
p_result += elementsize ;
}
while( secondhalf < endofsecondhalf){
memcopy(p_result , secondhalf , elementsize ) ;
secondhalf += elementsize ;
p_result += elementsize ;
}
memcopy(data,resultbuffer, n * elementsize) ;
free(resultbuffer) ;
}