-
-
Save kassane/bac1bd52d874e55a5fcc to your computer and use it in GitHub Desktop.
generic qsort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
void qsort(void *v[], int esq, int dir, | |
int(*comp)(void *, void *)) | |
{ | |
int i, ultimo; | |
void troca(void * v[], int i, int j); | |
if(esq >= dir) | |
return; | |
troca(v, esq, (esq + dir) / 2); | |
ultimo = esq; | |
for(i = esq + 1; i <= dir; i++) | |
{ | |
if((*comp)(v + i, v + esq) < 0) | |
troca(v, ++ultimo, i); | |
} | |
troca(v, esq, ultimo); | |
qsort(v, esq, ultimo - 1, comp); | |
qsort(v, ultimo + 1, dir, comp); | |
} | |
void troca(void *v[], int i, int j) | |
{ | |
void *temp; | |
temp = v[i]; | |
v[i] = v[j]; | |
v[j] = temp; | |
} | |
int compare(const void * a, const void * b) | |
{ | |
return (*(int*)a - *(int*)b); | |
} | |
int main() | |
{ | |
int v[] = {20, 10, 15, 5}; | |
int tam_v = sizeof(v) / sizeof(int); | |
int i; | |
qsort((void *)v, 0, tam_v - 1, (int(*)(void*, void*))compare); | |
for(i = 0; i < tam_v; i++) | |
printf("%d ", v[i]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment