使用qsort函数排序各种类型的数据。

1、使用qsort函数排序各种类型的数据。

int cmp(const void *x, const void *y) //整型
{
	return (*(int*)x) - (*(int *)y);
}

int cmp1(const void *x, const void *y) //字符型
{
	return (*(char *)x) - (*(char *)y);
}

int cmp2(const void *x, const void* y) //字符串型
{
	return strcmp(*(char **)x, *(char **)y);
}

int cmp3(const void *x, const void *y) //浮点型
{
	return (*(double*)x) - (*(double*)y);
}

int main()
{
	int i = 0;
	int arr1[] = { 1, 23, 45, 32, 42, 54, 2, 47, 86 };
	qsort(arr1, sizeof(arr1) / sizeof(arr1[0]), sizeof(arr1[0]), cmp);
	for (i = 0; i < sizeof(arr1) / sizeof(arr1[0]); i++)
	{
		printf("%d ", arr1[i]);
	}
	printf("\n");

	char arr2[] = { 'a','f','g','h','R','Y','W' };
	qsort(arr2, sizeof(arr2) / sizeof(arr2[0]), sizeof(arr2[0]), cmp1);
	for (i = 0; i < sizeof(arr2) / sizeof(arr2[0]); i++)
	{
		printf("%d ", arr2[i]);
	}
	printf("\n");

	char *arr3[] = {"asd","tfs","TF","hgf","uh","DFE"};
	qsort(arr3, sizeof(arr3) / sizeof(*arr3), sizeof(*arr3), cmp2);
	for (i = 0; i < sizeof(arr3) / sizeof(*arr3); i++)
	{	
		printf("%s ", arr3[i]);
	}
	printf("\n");

	double arr4[] = { 4.3, 23.2, 45.7, 32.66, 42.34, 54.78, 2.70, 47.6, 86.6 };
	qsort(arr4, sizeof(arr4) / sizeof(arr4[0]), sizeof(arr4[0]), cmp3);
	for (i = 0; i < sizeof(arr4) / sizeof(arr4[0]); i++)
	{
		printf("%f ", arr4[i]);
	}
	printf("\n");
	getchar();
	return 0;
}

你可能感兴趣的:(C语言)