Swap items of void* pointer array without memcpy in C -
i writing school project, , need swap 2 items of void* pointer array. can following code:
void swap(void *base, int len, int width) { void *p = malloc(width); memcpy(p,base,width); memcpy(base,(char*)base+width,width); memcpy((char*)base+width,p,width); free(p); }
but need swap items without memcpy, malloc, realloc , free. possible?
thank you
why don't swap in way?:
void swap(void *v[], int i, int j) { void *temp; temp = v[i]; v[i] = v[j]; v[j] = temp; }
as qsort (swaps elements within array):
void sort(void *v[], int left, int right, int (*comp)(const void *, const void *)) { int i, last; if (left >= right) return; swap(v, left, (left + right) / 2); last = left; (i = left + 1; <= right; i++) { if ((*comp)(v[i], v[left]) < 0) swap(v, ++last, i); } swap(v, left, last); sort(v, left, last - 1, comp); sort(v, last + 1, right, comp); }
Comments
Post a Comment