qsort的使用

一、了解qsort

(1)编译器函数库万能数组排序函数排序函数。

它是基于快速排序算法,所以是q sort。q 指的是 quick。快速

qsort 的函数原型是

void qsort(void*base,size_t num,size_t width,int(__cdecl*compare)(const void*,const void*));

各参数:

base :  待排序数组首地址,通常该位置传入的是一个数组名
num: 该数组的元素个数
width: 该数组中每个元素的大小(字节数)
(*compar)(const void *, const void *) : 此为指向比较函数的函数指针,决定了排序的顺序。正序或倒序。

二、compar参数

这里的compar是一个回调函数

回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。

所以注意这里的这个参数是一个指针。

compar只是一个函数名,你可以自己定义随意一个名字,但实现的内容是决定qsort所排序的顺序是从大到小还是从小到大。

//C语言

//compar的创建
int compare(const void* min,const void* max) {
	return (*(int*)max > *(int*)min);//从大到小
}

//这是一个 int 类型的函数。你需要根据数组的类型来修改这个函数的类型

      !!!!正确编写compar函数是实现qsort主要的环节 !!!!

三、常见的使用例子

这里举一个常见排序的例子,帮助理解。

//C语言

#define  _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int compare(const void* min,const void* max) {
	return (*(int*)max > *(int*)min);
}
void main() {
	int arr[] = { 10,30,40,90,80,45,75,97,122,84 };
	int sor = 0;
	qsort(arr,10,4,compare);
	while (sor<10)
	{
		printf("%d\t",arr[sor]);
		++sor;
	}
	printf("\n");
	system("pause");
}

四、排序各种类型的数据。

上面写的例子只是一个简单的例子,实现一个int型的数组排序。但是如果是一个字符数组呢?或者字符串数组呢?这里指的注意的就是传变量大小size的时候,应该传多大。下面来介绍。

字符数组的排序

//C语言

//字符数组的排序
int compare_ch(const void* min,const void* max) {
	return (*(char*)max > *(char*)min);
}

void main() {
	
	int sor = 0;
        char arr[] = { 'a','k','r','e','g','l' };
	qsort(arr,sizeof(arr),1,compare_ch);//元素大小是 1 !
	while (sor<6)
	{
		printf("%c\t",arr[sor]);
		++sor;
	}
	printf("\n");
	system("pause");
}

字符串的排序

//C语言
int compare_str(const void* min,const void* max) {
	return (*(char**)max > *(char**)min);
}
int main() {
	int sor = 0;
	char* str[] = { "i","am","a","student" };
	qsort(str,4,7,compare_str);
	while (sor<4) {
		printf("%s ",str[sor]);
		++sor;
	}
	printf("\n");
	return 0;
}

五、冒泡实现qsort原理

//C语言


void swap(char* one, char* other, size_t width) {
	size_t temp = 0;
	while (temp < width)
	{
		char some = *one;
		*one = *other;
		*other = some;
		++one;
		++other;
		++temp;
	}
}
int compare(const void* min,const void* max) {
	return *(char*)min > *(char*)max;
}
void bubble_sort(void* any,size_t num,size_t width, int(__cdecl*compare)(const void*, const void*)) {
	size_t row = 0;

	while (row < num)
	{
		size_t col = 0;
		while (col < num - 1 - row)
		{
			if ((compare((char*)any + col * width, (char*)any + (col + 1)*width)) > 0) {
				swap((char*)any + col * width, (char*)any + (col + 1)*width, width);
			}
			++col;
		}
		++row;
	}
}


 
  • 14
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值