实现全能的qsort,既能实现结构体排序,又能排int,double,等等
错误的原因是没有考虑到自己定义的cmp函数的返回值是0 和1
main.c
#include "qsort.h"
int cmp(const void *p1, const void *p2){
return *(int *)p1 < *(int *)p2;
}
void show(int size,int a[]){
int i = 0;
for(i = 0; i < size; ++i){
printf("%d ",a[i]);
}
printf("\n");
}
int main(void)
{
int a[] = {20,3,1,4,5,6,7,9,8,0};
int size = sizeof(a) / sizeof(a[0]);
show(size, a);
myqsort(a,size,sizeof(a[0]),cmp);
show(size, a);
// printf("%d %d %d\n",a[0],a[1],a[2]);
return 0;
}
qsort.c
/*#include "qsort.h"
void hqsort(void *base,size_t left,size_t right,int size,int (*compar)(const void *, const void *)){
size_t mid = (left + right) / 2;
size_t p = mid;
void* pivot = malloc(size);
memcpy(pivot, base + size * mid, size);
size_t i = left,j = right;
while (i < j){
for (; !(i >= p || compar(pivot, base + i * size) > 0); ++i); // 在这里用<0的判断纠结了半天
if (i < p){
memcpy(base + p * size, base + i * size, size);
p = i;
}
for (; !(j <= p || compar( base + j * size , pivot) < 0); --j);
if (j > p){
memcpy(base + p * size, base + j * size, size);
p = j;
}
// printf("i = %u j = %u\n",i,j);
}
memcpy(base + p * size, pivot,size);
free(pivot);
pivot = NULL;
if(p - left > 1){
hqsort(base, left, p - 1, size, compar);
}
if(right - p > 1){
hqsort(base, p + 1,right, size, compar);
}
}
void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *)){
hqsort(base, 0, nmemb - 1,size,compar);
}*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "qsort.h"
void quick_sort (void* base, size_t left,
size_t right, size_t size,
int (*compar) (const void*, const void*)) {
size_t p = (left + right) / 2;
void* pivot = malloc (size);
memcpy (pivot, base + p * size, size);
size_t i = left, j = right;
while (i < j) {
for (; ! (i >= p || compar (pivot,
base + i * size) == 1); ++i);
// printf("%d %d %d\n",*(int *)pivot,*(int *)(base + i * size),compar (pivot,
// base + i * size) );
if (i < p) {
// printf("%d %d\n",*(int *)(base+p*size),*(int *)(base+i*size));
memcpy (base + p * size,
base + i * size, size);
p = i;
}
for (; ! (j <= p || compar (base + j * size,
pivot) == 1); --j);
// printf("%d %d %d\n",*(int *)pivot,*(int *)(base + j * size),compar (pivot,
// base + j * size) );
if (j > p) {
memcpy (base + p * size,
base + j * size, size);
p = j;
}
}
memcpy (base + p * size, pivot, size);
free (pivot);
/* int k = 0;
for (k = 0;k < 10;k++){
printf("%d ",*(int *)(base + k * size) );
}
printf("\n");*/
pivot = NULL;
if (p - left > 1)
quick_sort (base, left, p - 1, size,
compar);
if (right - p > 1)
quick_sort (base, p + 1, right, size,
compar);
}
void myqsort (void* base, size_t nmemb,
size_t size, int (*compar) (const void*,
const void*)) {
quick_sort (base, 0, nmemb - 1, size, compar);
}
qsort.h
#ifndef __QSORT_H__
#define __QSORT_H__
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void myqsort(void *, size_t, size_t, int(*)(const void *,const void *));
#endif