www.zhblog.net

qsort排序

使用qsort进行排序:

1.排序int数组

2.排序字符串数组

3.根据结构体中的int排序

4.根据结构体中的char *排序


struct point {
int x;
char *name;
};
typedef struct point PT;

int cmpi(void *v, void *o) {
int m = *(int *) v;
int n = *(int *) o;
if (m < n) {
return -1;
} else if (m == n) {
return 0;
} else if (m > n) {
return 1;
}
}

int cmps(void *v, void *o) {
char *m = *(char **) v;
char *n = *(char **) o;
return strcmp(m, n);
}

int cmpsti(void *v, void *o) {
PT *m = (PT *) v;
PT *n = (PT *) o;
if (m->x < n->x) {
return -1;
} else if (m->x == n->x) {
return 0;
} else if (m->x > n->x) {
return 1;
}
}

int cmpsts(void *v, void *o) {
PT *m = (PT *) v;
PT *n = (PT *) o;
return strcmp(m->name, n->name);
}

int main() {
// int
int base[] = {3, 5, 8, 0, 1, 4, 7, 12, 54, 37};
qsort(base, sizeof(base) / sizeof(int), sizeof(int), (int (*)(const void *, const void *)) cmpi);
for (int i = 0; i < 10; ++i) {
printf("%d\t", base[i]);
}
printf("\n---------------------\n");
// char *
char *s[] = {"bbb", "eee", "aaa", "ccc"};
qsort(s, sizeof(s) / sizeof(s[0]), sizeof(s[0]), (int (*)(const void *, const void *)) cmps);
for (int i = 0; i < 4; ++i) {
printf("%s\t", s[i]);
}
printf("\n---------------------\n");
// struct int
PT pts[3] = {{2, "aaa"}, {1, "ccc"}, {3, "bbb"}};
qsort(pts, sizeof(pts) / sizeof(pts[0]), sizeof(pts[0]), (int (*)(const void *, const void *)) cmpsti);
for (int j = 0; j < 3; ++j) {
printf("%d - %s\t", pts[j].x, pts[j].name);
}
printf("\n---------------------\n");
// struct char *
PT ptc[3] = {{2, "aaa"}, {1, "ccc"}, {3, "bbb"}};
qsort(ptc, sizeof(ptc) / sizeof(ptc[0]), sizeof(ptc[0]), (int (*)(const void *, const void *)) cmpsts);
for (int j = 0; j < 3; ++j) {
printf("%d - %s\t", ptc[j].x, ptc[j].name);
}
}

 

 结果:

0    1    3    4    5    7    8    12    37    54    

---------------------

aaa    bbb    ccc    eee    

---------------------

1 - ccc    2 - aaa    3 - bbb    

---------------------

2 - aaa    3 - bbb    1 - ccc    


 

 

 

 

 

展开阅读全文

评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 心情