stdlib.h函数积累

1.void qsort( void * base , size_t num , size_t width ,

int (__cdecl * compare )(const void * elem1 , const void * elem2 ) );

用于对一串数据进行排序。

例子:

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int int_cmp(const void* p1, const void* p2)
{
	return *(int*)p1 - *(int*)p2;
}
void test01()
{
	int arr[] = { 1, 3, 5, 7, 9,2, 4, 6, 8,0 };
	int len = sizeof(arr) / sizeof(arr[0]);
	qsort(arr, len, sizeof(int), int_cmp);
	for (int i = 0; i < len; i++)
	{
		printf("%d ", arr[i]);
	}
}

int char_cmp(const void* p1, const void* p2)
{
	return *(char*)p1 - *(char*)p2;
}

void test02()
{
	char ch[] = "qwertyuiopasdfghjklzxcvbnm";
	int len = strlen(ch);
	qsort(ch, len, sizeof(ch[0]), char_cmp);
	puts(ch);
}

int main()
{
	test01();
	test02();
	return 0;
}

qsort的模拟实现(以冒泡排序为例):

cpp 复制代码
int int_cmp(const void * p1, const void * p2)
{
    return (*( int *)p1 - *(int *) p2);
}
void _swap(void *p1, void * p2, int size)
{
    int i = 0;
    for (i = 0; i< size; i++)
    {
        char tmp = *((char *)p1 + i);
        *(( char *)p1 + i) = *((char *) p2 + i);
        *(( char *)p2 + i) = tmp;
    }
}
void bubble(void *base, int count , int size, int(*cmp )(void *, void *))
{
 int i = 0;
 int j = 0;
     for (i = 0; i< count - 1; i++)
     {
         for (j = 0; j<count-i-1; j++)
         {
             if (cmp ((char *) base + j*size , (char *)base + (j + 1)*size) > 0)
             {
                 _swap(( char *)base + j*size, (char *)base + (j + 1)*size, size);
             }
         } 
     }
}

2.int atoi( const char *string );

将一串为字符串的数字转化为整型的数据。(可识别正负)

**返回值:**若字符串中无数字则返回0;若字符串中有数字提取并按顺序以整形的方式返回这些数字。

模拟实现:

cpp 复制代码
int myAtoi(char* str)
{
	int flag = 1;
	assert(str);
	while ((!isdigit(*str)) && *str != '-')
	{
		str++;
	}
	if(*str == '-')
	{
		flag = -1;
		str++;
	}
	long long ret = 0;
	while (isdigit(*str))
	{
		ret = ret * 10 + (*str - '0') * flag;
		if (ret > INT_MAX || ret < INT_MIN)
		{
			return 0;
		}
		str++;
	}
	return ret;
}
相关推荐
云知谷23 分钟前
【C++基本功】C++适合做什么,哪些领域适合哪些领域不适合?
c语言·开发语言·c++·人工智能·团队开发
电子_咸鱼1 小时前
LeetCode——Hot 100【电话号码的字母组合】
数据结构·算法·leetcode·链表·职场和发展·贪心算法·深度优先
仰泳的熊猫1 小时前
LeetCode:785. 判断二分图
数据结构·c++·算法·leetcode
rit84324991 小时前
基于MATLAB实现基于距离的离群点检测算法
人工智能·算法·matlab
my rainy days3 小时前
C++:友元
开发语言·c++·算法
haoly19893 小时前
数据结构和算法篇-归并排序的两个视角-迭代和递归
数据结构·算法·归并排序
微笑尅乐3 小时前
中点为根——力扣108.讲有序数组转换为二叉搜索树
算法·leetcode·职场和发展
im_AMBER4 小时前
算法笔记 05
笔记·算法·哈希算法
夏鹏今天学习了吗4 小时前
【LeetCode热题100(46/100)】从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
吃着火锅x唱着歌4 小时前
LeetCode 2389.和有限的最长子序列
算法·leetcode·职场和发展