qsort

void qsort (void* base, size_t num, size_t size,
int (*compar)(const void*,const void*));

Sort elements of array

Sorts the num elements of the array pointed to by base, element size, each element size bytes long, using the compar function to determine the order.

The sorting algorithm used by this function compares pairs of elements by calling the specified compar function with pointers to them as argument.(函数指针作为参数)

The function does not return any value, but modifies the content of the array pointed to by base reordering its elements as defined by compar.

The order of equivalent elements is undefined.

Parameters

1.base

Pointer to the first object of the array to be sorted, converted to a void*.

2.num

Number of elements in the array pointed to by base.
size_t is an unsigned integral type.

3.size

Size in bytes of each element in the array.
size_t is an unsigned integral type.

4.compar

Pointer to a function that compares two elements.

This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:

int compar (const void* p1, const void* p2);

Taking two pointers as arguments (both converted to const void*). The function defines the order of the elements by returning (in a stable and transitive manner):

return value meaning
<0 The element pointed to by p1 goes before the element pointed to by p2
0 The element pointed to by p1 is equivalent to the element pointed to by p2
>0 The element pointed to by p1 goes after the element pointed to by p2

For types that can be compared using regular relational operators, a general compar function may look like:

int compareMyType (const void * a, const void * b)
{
if ( *(MyType*)a < *(MyType*)b ) return -1;
if ( *(MyType*)a == *(MyType*)b ) return 0;
if ( *(MyType*)a > *(MyType*)b ) return 1;
}

Return Value

none

Example

/* qsort example */
#include <stdio.h> /* printf */
#include <stdlib.h> /* qsort */ int values[] = { 40, 10, 100, 90, 20, 25 }; int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
} int main ()
{
int n;
qsort (values, 6, sizeof(int), compare);
for (n=0; n<6; n++)
printf ("%d ",values[n]);
return 0;
}

Output:

10 20 25 40 90 100

Complexity

Unspecified, but quicksorts are generally linearithmic in num, on average, calling compar approximately num*log2(num)times.

Data races

The function accesses and/or modifies the num elements in the array pointed to by base.

Exceptions (C++)

If comp does not throw exceptions, this function throws no exceptions (no-throw guarantee).

If base does not point to an array of at least num*size bytes, or if comp does not behave as described above, it causes undefined behavior.


bsearch

void* bsearch (const void* key, const void* base,
size_t num, size_t size,
int (*compar)(const void*,const void*));

Binary search in array

Searches the given key in the array pointed to by base (which is formed by num elements, each of size bytes), and returns a void* pointer to a matching element, if found.

To perform the search, the function performs a series of calls to compar with key as first argument and elements of the array pointed to by base as second argument.

Because this function may be optimized to use a non-linear search algorithm (presumably a binary search), the elements that compare less than key using compar should precede those that compare equal, and these should precede those that compare greater. This requirement is fulfilled by any array ordered with the same criteria used by compar(as if sorted with qsort).

Parameters

key

Pointer to the object that serves as key for the search, type-casted to a void*.

base

Pointer to the first object of the array where the search is performed, type-casted to a void*.

num

Number of elements in the array pointed to by base.
size_t is an unsigned integral type.

size

Size in bytes of each element in the array.
size_t is an unsigned integral type.

compar

Pointer to a function that compares two elements.

This function is called repeatedly by bsearch to compare key against individual elements in base. It shall follow the following prototype:

int compar (const void* pkey, const void* pelem);

Taking two pointers as arguments: the first is always key, and the second points to an element of the array (both type-casted to const void*). The function shall return (in a stable and transitive manner):

return value meaning
<0 The element pointed to by pkey goes before the element pointed to by pelem
0 The element pointed to by pkey is equivalent to the element pointed to by pelem
>0 The element pointed to by pkey goes after the element pointed to by pelem

For types that can be compared using regular relational operators, a general compar function may look like:

int compareMyType (const void * a, const void * b)
{
if ( *(MyType*)a < *(MyType*)b ) return -1;
if ( *(MyType*)a == *(MyType*)b ) return 0;
if ( *(MyType*)a > *(MyType*)b ) return 1;
}

Return Value

A pointer to an entry in the array that matches the search key. If there are more than one matching elements (i.e., elements for which compar would return 0), this may point to any of them (not necessarily the first one).

If key is not found, a null pointer is returned.

Example

/* bsearch example */
#include <stdio.h> /* printf */
#include <stdlib.h> /* qsort, bsearch, NULL */ int compareints (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
} int values[] = { 50, 20, 60, 40, 10, 30 }; int main ()
{
int * pItem;
int key = 40;
qsort (values, 6, sizeof (int), compareints);
pItem = (int*) bsearch (&key, values, 6, sizeof (int), compareints);
if (pItem!=NULL)
printf ("%d is in the array.\n",*pItem);
else
printf ("%d is not in the array.\n",key);
return 0;
}

In the example, compareints compares the values pointed to by the two parameters as int values and returns the result of subtracting their pointed values, which gives 0 as result if they are equal, a positive result if the value pointed to by ais greater than the one pointed to by b or a negative result if the value pointed to by b is greater.

In the main function the target array is sorted with qsort before calling bsearch to search for a value.

Output:

40 is in the array.

For C strings, strcmp can directly be used as the compar argument for bsearch:

/* bsearch example with strings */
#include <stdio.h> /* printf */
#include <stdlib.h> /* qsort, bsearch, NULL */
#include <string.h> /* strcmp */ char strvalues[][20] = {"some","example","strings","here"}; int main ()
{
char * pItem;
char key[20] = "example"; /* sort elements in array: */
qsort (strvalues, 4, 20, (int(*)(const void*,const void*)) strcmp); /* search for the key: */
pItem = (char*) bsearch (key, strvalues, 4, 20, (int(*)(const void*,const void*)) strcmp); if (pItem!=NULL)
printf ("%s is in the array.\n",pItem);
else
printf ("%s is not in the array.\n",key);
return 0;
}

Output:

example is in the array.

Complexity

Unspecified, but binary searches are generally logarithmic in num, on average, calling compar approximately log2(num)+2 times.

Data races

The function accesses the object pointed to by key and any number of the num elements in the array pointed to by base, but does not modify any of them.

Exceptions (C++)

If comp does not throw exceptions, this function throws no exceptions (no-throw guarantee).

If key does not point to an object size bytes long, or if base does not point to an array of at least num properly arranged elements of size bytes each, or if comp does not behave as described above, it causes undefined behavior.

qsort()和bsearch()的更多相关文章

  1. stdlib.h中自带的两个算法qsort,bsearch

    http://zh.cppreference.com/w/c/algorithm ========== void qsort( void *ptr, size_t count, size_t size ...

  2. C语言标准库 qsort bsearch 源码实现

    C语言是简洁的强大的,当然也有很多坑.C语言也是有点业界良心的,至少它实现了2个最最常用的算法:快速排序和二分查找. 我们知道,对于C语言标准库 qsort和 bsearch: a. 它是“泛型”的, ...

  3. 在stm32开发可以调用c标准库的排序和查找 qsort bsearch

    在嵌入式开发中,可以使用c标准库自带的库函数,而不用自己去早轮子,qsort 和bsearch就是其中的两个比较好用的 二分法查找,前提是已经排序好的数据.下面的代码, 如果数据为排序,则要进行排序后 ...

  4. Bjarne Stroustrup对C++程序员的忠告

    转自:http://blog.csdn.net/adm_qxx/archive/2007/05/20/1617488.aspx  第1章 致读者  [1] 在编写程序时,你是在为你针对某个问题的解决方 ...

  5. 5.24 Declaring Attributes of Functions【转】

    转自:https://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html 5.24 Declaring Attributes o ...

  6. HDoj-2072-字数

    字数 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submiss ...

  7. poj 2804 字典 (特里 要么 快排+二分法)

    2804:词典 总时间限制:  3000ms  内存限制:  65536kB 描写叙述 你旅游到了一个国外的城市.那里的人们说的外国语言你不能理解.只是幸运的是,你有一本词典能够帮助你. 输入 首先输 ...

  8. 07--STL序列容器(Array)

    一:Array了解 array<T,N> 模板定义了一种相当于标准数组的容器类型.它是一个有 N 个 T 类型元素的固定序列.除了需要指定元素的类型和个数之外,它和常规数组没有太大的差别. ...

  9. 05--STL序列容器(List)

    一:List双向链表简介 list是一个双向链表容器,可高效地进行插入删除元素. list不可以随机存取元素,所以不支持at.(pos)函数与[]操作符.It++(ok) it+5(err)list不 ...

随机推荐

  1. Luogu P4478 [BJWC2018]上学路线 卢卡斯+组合+CRT

    首先,从$(0,0)$走到$(n,m)$的方案数是$ C_{n+m}^n$,可以把走的方向看作一种序列,这个序列长$ n+m$ ,你需要从中任取$n$个位置,让他向右走: 然后就是如何处理不能走的点: ...

  2. Java文件与io——File类

    概念: File类:表示文件和目录路径名的抽象表示形式. File类可以实现文件的创建.删除.重命名.得到路径.创建时间等等,是唯一与文件本身有关的操作类. 例: public class FileD ...

  3. 详细介绍VO(值对象)和PO(持久对象)的区别

    VO,值对象(Value Object),PO,持久对象(Persisent Object),它们是由一组属性和属性的get和set方法组成.从结构上看,它们并没有什么不同的地方.但从其意义和本质上来 ...

  4. swift第一课快速体验playground

    最近听说苹果要大力推行swift语言,所以我必须要赶快好好学一学,今天做第一个就遇到问题. 在Xcode7.2欢迎界面,选中创建第一个,我们一般都是默认创建第二个. 创建完后,出现问题了,提示如下: ...

  5. Java 打印PDF文档的3种情况

    以下内容归纳了通过Java程序打印PDF文档时的3种情形.即: 静默打印 显示打印对话框打印 打印PDF时自定义纸张大小 使用工具:Spire.PDF for Java Jar导入: 方法1:通过官网 ...

  6. css最佳实践(reset.css)

    html, body, div, span, object, iframe,h1, h2, h3, h4, h5, h6, p, blockquote, pre,abbr, address, cite ...

  7. 【干货】JavaScript DOM编程艺术学习笔记10-12【完】

    十.用JavaScript实现动画效果 鼠标放到链接上,每次只显示图片的一小部分,加快加载速度. js: function prepareSlideshow(){ //对象检测 if(!documen ...

  8. 【迷你微信】基于MINA、Hibernate、Spring、Protobuf的即时聊天系统:9.观察者模式

    欢迎阅读我的开源项目<迷你微信>服务器与<迷你微信>客户端 前言 在一个程序的迭代过程中,复杂度渐渐上升,可能会出现一些跨模块的调用的需求,若是直接得到引用来进行使用,会导致模 ...

  9. <转载>为什么VR不可能成功?

    这是一个来自Quora的回答,我把要点总结翻译了下,供大家参考批判. How big and issue the nausea problem for Virtual Reality products ...

  10. oracle最高账号sys的密码认证模式

    CONNECT USERNAME/PASSWORD@SERVERNAME AS SYSDBAconnect 是指连接到username是指用户名password是指密码servername是指服务名a ...