Sorting any kind of element using void pointers in C -
hello writing program sorting general element in c. can sort type of object(int,float,complex number, objects)
what have thought of using void pointers,
void qsort(void *ptr,int sz,int i,int j,int (*fptr) (const void *,const void *) ) { if(i<j) { int p=(i+j)/2; p=partition(ptr,sz,i,j,p,fptr); qsort(ptr,size,i,p-1,fptr); qsort(ptr,size,p+1,j,fptr); } } for comparison
by value of sz know whether pointer string,int,char,float,etc
int compare(const void* a,const void* b,int sz) { if(sz==0) //means pointer string return strcmp( (char*)a, (char*)b ); else if(sz==1) //means int return *(int*)a - *(int*)b; else if(sz==2) //means float return *(float*)a- *(float*)b; else if(sz==3) return *(char*)a- *(char*)b; } for swapping 2 elements
void swap(void *a,void *b,int sz)//for swapping { if(sz==0) { void *c; c=a; a=b; b=c; } else if(sz==1) { a=(int*)a; b=(int*)b; int c; c= *a; *a=*b; *b=c; } else if(sz==2) { a=(float*)a; b=(float*)b; float c; c= *a; *a=*b; *b=c; } edited
qsort(arr,4,0,9,&compare);
the full code under construction, please tell me if there optimizations in approach, or better alternatives problem. seems me going big in size
many many thanx in advance
since swap routine used partition function, should work arbitrary sized objects, not ones plan pass in code.
void swap (void *a, void *b, int sz) { char buf[512]; void *p = buf; if (sz > sizeof(buf)) p = malloc(sz); memcpy(p, a, sz); memcpy(a, b, sz); memcpy(b, p, sz); if (p != buf) free(p); } from way have written comparison routine, seems plan send in types of arrays. but, sz used tell how big individual elements in array are, not type identifier, seem trying use it.
struct x { int key; /*...*/ }; int cmp_x (const void *a, const void *b) { const struct x *xa = a; const struct x *xb = b; return (xa->key > xb->key) - (xa->key < xb->key); } struct x array_x[100]; /* populate array */ qsort(array_x, sizeof(struct x), 0, 100, cmp_x); this how imagine qsort should called. (thanks ambroz bizjak nifty comparison implementation.)
for array of int:
int cmp_int (const void *a, const void *b) { int ia = *(const int *)a; int ib = *(const int *)b; return (ia > ib) - (ia < ib); } int array_i[100]; /* populate array */ qsort(array_i, sizeof(int), 0, 100, cmp_int);
Comments
Post a Comment