Question:
How would you qsort() function to sort an array of structures?
Answer:
Source: CoolInterview.com
#include<stdio.h> #include<stdlib.h>
typedef struct emp_list { int id; char name[10]; }EMP;
int sorting_mech( const void *ele1 , const void *ele2) {
int a,b; a = *((int *)ele1); b = *((int *)ele2);
if( a > b) { return 1; } if(a < b ) { return -1; } return 0; }
int sorting_mech_emp( const void *ele1 , const void *ele2) {
EMP a,b; a = *((EMP *)ele1); b = *((EMP * )ele2);
if(a.id > b.id ) { return 1; } else { return -1; } return 0; } int main() {
int numbers[6] = {1,2,6,5,8,3}; EMP list[3] = { {10,"prash"} , {8,"praz"} , {1,"pra"} }; int i = 0; int tot_ele; int struct_array_elements; tot_ele = sizeof(numbers) / sizeof(int); struct_array_elements = sizeof(list) /sizeof(EMP); printf("before sorting "); for(i=0 ; i<tot_ele;i++ ) { printf("%d ",numbers[i]); printf(" "); } qsort(( void * )numbers , tot_ele , sizeof(int) , sorting_mech ); printf("after the sorting !! "); for(i=0 ; i<tot_ele;i++ ) { printf("%d ",numbers[i]); printf(" "); } /* added currently*/
printf("before the sorting !! ");
for(i=0;i<struct_array_elements;i++ ) { printf(" id: %d name: %s",list[i].id,list[i].name); printf("
"); }
qsort((void *)list,struct_array_elements,sizeof(EMP),sorting_mech_emp);
printf("after the sorting !!! "); for(i=0;i<struct_array_elements;i++ ) { printf(" id: %d name: %s",list[i].id,list[i].name); printf("
");
}
return 0; }
Source: CoolInterview.com
Answered by: prashanjit | Date: 8/11/2008
| Contact prashanjit
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
- There should not be any Spelling Mistakes.
- There should not be any Gramatical Errors.
- Answers must not contain any bad words.
- Answers should not be the repeat of same answer, already approved.
- Answer should be complete in itself.
|