构成
NAME
qsort, qsort_r - sort an array
SYNOPSIS
#include <stdlib.h>
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
参数:
- 数组地址
- 数组长度
- 数组每个元素的大小
- 一个函数指针(比较数组两个元素大小的函数)
原理
利用栈数据结构模拟递归调用,堆空间的大小远远大于栈空间,避免栈溢出
性能
时间复杂度:平均和最好O (logn * n),最坏O (n^2)
空间复杂度:O(logn)
qsort排序数组的代码
输入:数组地址,数组长度,数组元素的大小,比较函数指针
输出:升序排列的数组
qsort.c (比较数组元素大小的函数)
#include <string.h>
//比较字符串数组中的元素
int compare_arr(const void *p1, const void *p2)
{
const char *pLeft = (const char *)p1;
const char *pRight = (const char *)p2;
return strcmp(pLeft, pRight);
}
//比较索引数组中的元素
int compare_index(const void *p1, const void *p2)
{
const char *pLeft = *(const char **)p1;
const char *pRight = *(const char **)p2;
return strcmp(pLeft, pRight);
}
print.c (打印数组元素的函数)
#include <stdio.h>
void print_chars_arr(char (*arr)[100], int len)
{
for (int i = 0; i < len; ++i) {
printf("%s\n", arr[i]);
}
}
void print_index_arr(char **ppArr, int len)
{
for (int i = 0; i < len; ++i) {
printf("%s\n", ppArr[i]);
}
}
test_sort.c
#include <stdio.h>
#include <stdlib.h>
int compare_arr(const void *p1, const void *p2);
int compare_index(const void *p1, const void *p2);
void print_chars_arr(char (*arr)[100], int len);
void print_index_arr(char **ppArr, int len);
void test_qsort1()
{
//直接排序字符串数组
char wordbook[][100] = {
"hello",
"hero",
"abandon",
"wukong",
"loong",
"angle",
"pretty",
"handsome",
"vector"
};
int len = sizeof(wordbook) / sizeof(wordbook[0]);
print_chars_arr(wordbook, len);
//排序
qsort(wordbook, sizeof(wordbook) / sizeof(wordbook[0]), sizeof(wordbook[0]), compare_arr);
printf("\n排序后-----------------------\n");
print_chars_arr(wordbook, len);
}
void test_qsort2()
{
//排序索引数组
char wordbook[][100] = {
"hello",
"hero",
"abandon",
"wukong",
"loong",
"angle",
"pretty",
"handsome",
"vector"
};
int len = sizeof(wordbook) / sizeof(wordbook[0]);
printf("原数组-----------------------\n");
print_chars_arr(wordbook, len);
//构建索引数组
char **pArr = (char**)calloc(len, sizeof(char*));
//初始化索引数组
for (int i = 0; i < len; ++i) {
pArr[i] = wordbook[i];
}
printf("\n索引数组-----------------------\n");
print_index_arr(pArr, len);
qsort(pArr, len, sizeof(char*), compare_index);
printf("\n排序后的原数组-----------------------\n");
print_chars_arr(wordbook, len);
printf("\n排序后的索引数组-----------------------\n");
print_index_arr(pArr, len);
//释放索引数组
free(pArr);
pArr = NULL;
}
int main()
{
/* test_qsort1(); */
test_qsort2();
return 0;
}