qsort函数实现对一组任意类型对象的排序,调用者提供 findPos_t 回调函数,在回调函数中实现对特定类型元素位置的查找。
// qsort.h
#ifndef QSORT_H
#define QSORT_H
typedef int (*findPos_t)(void *a[], int left, int right);
extern void qsort(void *a[], int left, int right, findPos_t findPos);
#endif
// qsort.c
#include "qsort.h"
void qsort(void * a[], int left, int right, findPos_t findPos) {
int pos;
if(left < right) {
pos = findPos(a, left, right);
qsort(a, left, pos - 1, findPos);
qsort(a, pos + 1, right, findPos);
}
}
// qsortMain.c
#include <stdio.h>
#include "qsort.h"
typedef struct {
const char *name;
int score;
} student_t;
int findPos(void * a[], int left, int right) {
int val = *(int *)a[left];
while(left < right) {
while(left < right && val <= *(int *)a[right]) {
right --;
}
*(int *)a[left] = *(int *)a[right];
while(left < right && val >= *(int *)a[left]) {
left ++;
}
*(int *)a[right] = *(int *)a[left];
}
*(int *)a[left] = val;
return left;
}
int findPos_student(void * a[], int left, int right) {
student_t val = *(student_t *)a[left];
while(left < right) {
while(left < right && val.score <= ((student_t *)a[right])->score) {
right --;
}
*(student_t *)a[left] = *(student_t *)a[right];
while(left < right && val.score >= (*(student_t *)a[left]).score) {
left ++;
}
*(student_t *)a[right] = *(student_t *)a[left];
}
*(student_t *)a[left] = val;
return left;
}
int main(void) {
int i;
int data[5] = {1, 7, 4, 2, 5};
int *pdata[5] = {&data[0], &data[1], &data[2], &data[3], &data[4]};
qsort((void **)pdata, 0, 5 - 1, findPos);
for(i = 0; i < 5; i ++) {
printf("%d ", data[i]);
}
putchar('\n');
student_t list[4] = {{"Tom", 68}, {"Jerry", 72}, {"Moby", 60}, {"Kirby", 89}};
student_t *plist[4] = {&list[0], &list[1], &list[2], &list[3]};
qsort((void **)plist, 0, 4 - 1, findPos_student);
for(i = 0; i < 4; i ++) {
printf("%s %d\n", list[i].name, list[i].score);
}
return 0;
}