C/C++程序员:排序算法之标准C语言qsort函数简单用法介绍

标准库函数qsort
void qsort (
  void* base, // 任意类型数组的首地址
  size_t nmemb, // 数组元素个数
  size_t size, // 数组元素字节数
  int (*compar) (const void*, const void*) // 比较函数指针
);
其中compar参数指向一个形如:
int xxx (const void* a, const void* b);
的函数。该函数自己定义,其中完成如下判断:
if (a的目标 > b的目标)
  return 正数;
if (a的目标 < b的目标)
  return 负数;
if (a的目标 == b的目标)

  return 0;


#include 
#include 
#include 
void _myqsort (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) < 0); ++i);
		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;
		}
	}
	memcpy (base + p * size, pivot, size);
	free (pivot);
	if (p - left > 1)
		_myqsort (base, left, p - 1, size, compar);
	if (right - p > 1)
		_myqsort (base, p + 1, right, size, compar);
}
void myqsort (void* base, size_t nmemb,
	size_t size,
	int (*compar) (const void*, const void*)) {
	_myqsort (base, 0, nmemb - 1, size, compar);
}
int int_cmp (const void* a, const void* b) {
	return *(const int*)b - *(const int*)a;
}
int str_cmp (const void* a, const void* b) {
	return strcmp (*(const char* const*)a,
		*(const char* const*)b);
}
typedef struct Student {
	char name[256];
	int age;
}	STUDENT;
int stu_cmp (const void* a, const void* b) {
	const STUDENT* pa = (const STUDENT*)a;
	const STUDENT* pb = (const STUDENT*)b;
	int res = strcmp (pa->name, pb->name);
	if (! res)
		return pa->age - pb->age;
	return -res;
}
int main (void) {
	int na[] = {23, 45, 12, 27, 36, 88, 19, 55};
	size_t size = sizeof (na[0]);
	size_t nmemb = sizeof (na) / size;
	myqsort (na, nmemb, size, int_cmp);
	size_t i;
	for (i = 0; i < nmemb; ++i)
		printf ("%d ", na[i]);
	printf ("\n");
	const char* sa[] = {"beijing", "tianjin",
		"shanghai", "chongqing"};
	size = sizeof (sa[0]);
	nmemb = sizeof (sa) / size;
	myqsort (sa, nmemb, size, str_cmp);
	for (i = 0; i < nmemb; ++i)
		printf ("%s ", sa[i]);
	printf ("\n");
	STUDENT ta[] = {
		{"zgfei", 25},
		{"zun", 22},
		{"zhafei", 20},
		{"zhan", 23},
		{"guyu", 50}};
	size = sizeof (ta[0]);
	nmemb = sizeof (ta) / size;
	myqsort (ta, nmemb, size, stu_cmp);
	for (i = 0; i < nmemb; ++i)
		printf ("%s/%d ", ta[i].name, ta[i].age);
	printf ("\n");
	return 0;
}


你可能感兴趣的:(基础语法和语法分析)