使用VC库函数中的快速排序函数

qsort快排函数源代码 C语言qsort快排函数的模版,帮助深入认识模版的快速高效的风格。 立即下载

上一篇讲了快速排序的实现。但在很多场合,直接使用快速排序的库函数是很方便的。下面讲下VC中库函数qsort()的用法:

 

函数原型:

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

第一个是数组地址,第二是数组大小,第三个是数组中每个元素的字节数,最后一个是个函数指针,表示如何比较数组中的元素。

头文件 #include <stdlib.h>

 

 

下面分别就int等整数数据,double等浮点数据,结构体和类,按指定方式这四种情况进行讲解。

 

实例1   对int等整数数据进行排序

int cmp(const void *x, const void *y)
{
	return *(int*)x - *(int*)y;
}
qsort(a, MAXN, sizeof(a[0]), cmp); 

MAXN为数组大小,下同

 

实例2   对double等浮点数进行排序

int cmpDouble(const void *x, const void *y)
{
	return (*(double*)x > *(double*)y ? 1 : -1);
}
qsort(a, n, sizeof(a[0]), cmpDouble);

 

实例3  对结构体,类等复杂数据进行排序

如

struct Student
{
	char szName[30];
	int  nAge;
};

先对年龄排序,年龄相同再按姓名排序。

int cmpStudent (const void *x, const void *y)
{   //先作下指针转换,再按要求比较
	Student *pNodex = (Student*)x, *pNodey = (Student*)y;
	if (pNodex->nAge != pNodey->nAge)
		return pNodex->nAge - pNodey->nAge;
	else
		return strcmp(pNodex->szName, pNodey->szName);
}
qsort(a, n, sizeof(a[0]), cmpStudent);


实例4     按指定方式进行排序。

如对只有大小写字母的字符串"AajkuKdYUBCDwyz"进行排序,要求大写字母在前,小写字母在后。

int cmp1(const void *x, const void *y)
{
	char *pcx = (char*)x, *pcy = (char*)y;

	bool flag1 = *pcx >= 'A' && *pcx <= 'Z';
	bool flag2 = *pcy >= 'A' && *pcy <= 'Z';

	if(flag1 == flag2)    //如果都为大写字母或都为小写字母
		return *pcx - *pcy;
	else                  //否则,谁为大写字母,谁的权值小。
		return flag1 ? -1 : 1;
}
int main()
{
	char szText[] = "AajkuKdYUBCDwyz";
	qsort(szText, strlen(szText), sizeof(szText[0]), cmp1);
	printf("%s\n", szText);
	return 0;
}


 

 

VC中qsort源代码 VC中的qsort源代码,值得学习!这是我从网上搜集来的 立即下载

相关推荐

VC++排序方法

用C语言写的多种排序方法;并对它们的效率进行比较

VS qsort和sort函数

qsort函数功 能: 使用快速排序例程进行排序 头文件:stdlib.h 函数原型: void __cdecl qsort ( void *base, size_t num, size_t width, int (__cdecl *comp)(const void *, const void *) ) 参数说明:...

PtaQ的博客 2034

从数据手册到代码:一步步解读SC7A20寄存器配置与加速度值换算原理

本文详细解析了SC7A20三轴加速度传感器的寄存器配置与加速度值换算原理。从数据手册出发,逐步拆解关键寄存器设置,并推导原始ADC值到物理加速度的完整换算过程,帮助开发者深入理解传感器底层工作原理,提升嵌入式开发效率。

weixin_29179311的博客 376

学会快速排序库函数qsort的使用以及实现

qsort的使用和实现

qq_67838572的博客 260

DeepStream实战:多路视频AI分析从CPU瓶颈到GPU高吞吐

视频流智能分析在智慧交通和边缘计算中愈发关键,但传统CPU拉流解码加GPU推理的链路,常面临CPU占用过高、GPU利用率低下的窘境。DeepStream作为NVIDIA推出的流式推理框架,基于GStreamer插件生态,以NVMM内存管理让视频数据在GPU侧高效流转,配合NVDEC硬件解码、NvStreamMux多路批处理与TensorRT优化,大幅降低CPU负担并提升多路视频并行吞吐。针对1080p甚至更高分辨率的RTSP流,它能将多路帧汇聚为batch批量推理,从而支撑实时车辆识别、道路分析等生产级应用

weixin_29051245的博客 190

手把手教你用SAM模型实现精准图像分割:从环境配置到实战应用

本文详细介绍了如何使用Meta推出的Segment Anything Model(SAM)实现精准图像分割,从环境配置到实战应用的全流程。特别针对电商场景中的商品分割需求,提供了硬件配置、模型下载、API使用及优化策略等实用指南,帮助开发者快速掌握这一强大的深度学习工具。

pepsi的博客 1089

C++ 排序函数 sort(),qsort()的用法【转】

C++ 排序函数 sort(),qsort()的用法想起来自己天天排序排序,冒泡啊,二分查找啊,结果在STL中就自带了排序函数sort,qsort,总算把自己解脱了~所以自己总结了一下,首先看sort函数见下表:  函数名 功能描述  sort 对给定区间所有元素进行排序  stable_sort 对给定区间所有元素进行稳定排序  partial_sort 对给定区间所有元素部分排序  partial_sort_copy 对给定区间复制并排序  nth_element 找出给定区间的某个位置对应的元素  i

fanxing1的专栏 1018

k8s部署 普罗米修斯(Prometheus)监控

Prometheus是一个开源的服务监控系统和时序数据库其提供了通用的数据模型和快捷数据采集、存储和查询接口它的核心组件Prometheus服务器定期从静态配置的监控目标或者基于服务发现自动配置的目标中进行拉 取数据新拉取到啊的 数据大于配置的内存缓存区时,数据就会持久化到存储设备当中。

D2961953033的博客 3886

【C++】序论:qsort和sort函数详解

qsort函数是C语言提供的库函数,可以将任何无序数据排列成有序数据,本质上是通过指针移动和快速排序完成对数组内部数据的排序,并放回原数组中参数1:void* base指向未知类型的待排序数组参数2:size_t num,其中size_t是以字节为单位的数据类型,这个参数要传入数组中的元素个数参数3:size_t width,是数组类型的大小(sizeof(int))参数4:int(*compare)(const void* p1,const void* p2)

zwznzje的博客 4585

瑞萨芯片串口配置,基于RL78芯片的串口使用配置

在这里隆重给大家介绍瑞萨编辑器CS+ for CA 的自动生成代码功能,只需要配置几个参数,就可以得到你想要的串口配置了,我现在已经忘记怎么手动配置寄存器了,哈哈。选择设置,此时将端口设置成功接下来设置时钟,根据自己的芯片所需设置相应的时钟,自己芯片是什么时钟查看数据手册和原理图可以找到。瑞萨芯片的串口配置其实和ST芯片的串口配置差不多,只是ST芯片的中文数据手册比较多,就更好配置了,找到所需要的串口配置IO口,此时将UART0 配置为引脚P61和P62,瑞萨芯片的串口配置竟然要配置串口。

qq_45315904的博客 4315

lidar360 V8.0 & lidar360MLS V8.0雷达点云数据处理软件

机载林业 — 基于机载激光雷达点云数据提取一系列森林结构参数(如:高度分位数、叶面积指数、郁闭度等),分割单木并提取单木参数(包括树的位置、树高、胸径、枝下高、冠幅等属性),利用软件的多种回归分析功能可以结合地面调查数据反演森林生物量、蓄积量等功能参数。还可以生成等高线、山体阴影、坡度、坡向、粗糙度等多种产品。分类 — LiDAR360提供多种分类功能,包括地面点分类、模型关键点分类、选择区域地面点分类、机器学习模型分类(可高效地分离建筑、植被、路灯等通用类别)、深度学习模型分类、自定义深度学习分类等。

2403_83796253的博客 5197

C语言关于排序的十一个函数

1.二叉树 堆排序 O(nlogn) 满二叉树 叶子节点全部在同一个高度,且除了叶子节点外,所有的节点都有左右子节点 一棵高度为h的满二叉树,一共有(2^h-1)节点 平衡二叉树 从任意一个节点开始,它的左右子树的高度差不会超过1 完全二叉树 除了最后一层的叶子节点必须是从左到右,是一颗满二叉树 把数组看作是一个完全二叉树 把完全二叉树调整成大栈堆(小栈堆),从最后一个有子节点的节点(len...

weixin_42397177的博客 4960

ISO21434 组织网络安全管理(二)

为了实现网络安全工程,该组织建立并维护网络安全治理和网络安全文化,包括网络安全意识管理、能力管理和持续改进。这涉及到指定针对本文档的目标进行独立审计的特定于组织的规则和过程。 为了支持网络安全工程,该组织实施了网络安全的管理系统,包括管理工具和应用质量管理系统。

qq_42357877的博客 1336

利用VC/VS的安装目录找到C/C++库函数实现的源代码

2013-07-03 20:08:57 大多开发软件的装目录下都有很多有价值的东西,比如help文档、user guide、src文件等。今天在VS的安装目录下发现了库函数的源文件,这些文件中有对所有库函数的实现,是Microsoft Corporation写的,应该都是经过优化的,以后在需要自己实现这些函数时,可以作为参考。 我用的是VS2010,库函数的源文件目录为: D:\Progra...

weixin_33862993的博客 705

ESP32 双雷达融合盲区车辆接近预警系统设计与实现

/ 超声波传感器引脚// 触发引脚// 回声引脚// 预警模块引脚// 蜂鸣器引脚// LED引脚// 串口配置(毫米波雷达用UART2)#define BAUD_RATE 115200 // 雷达串口波特率(IWR6843默认配置)// 预警阈值(可根据实际需求调整)// 高危区阈值(3m)// 预警区阈值(10m)// 传感器数据存储// 毫米波雷达距离(m)// 毫米波雷达速度(km/h)// 超声波距离(m)// 融合后距离(m)

weixin_42300449的博客 751

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 白话经典算法系列之六 快速排序 快速搞定
下一篇: VC 为程序创建快捷方式的详细讲解
MoreWindows
MoreWindows 《白话经典算法》、《秒杀多线程》作者 《白话经典算法》、《秒杀多线程》作者 领域专家: 操作系统技术领域 领域专家: 操作系统技术领域
博客等级 码龄15年 2万+粉丝 157原创
评论 8
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址