高明网站设计服务,产品营销推广方式,锡林浩特网站建设开发,软文大全500篇qsort
编译器函数库自带的快速排序函数。
void qsort(void*base,size_t num,size_t width,int(__cdecl*compare)(const void*,const void*));
参数解释#xff1a;
void*base-待排序数组首地址size_t num-数组中待排序元素数量size_t width-各元素的占用空间大小int(__cde…qsort
编译器函数库自带的快速排序函数。
void qsort(void*base,size_t num,size_t width,int(__cdecl*compare)(const void*,const void*));
参数解释
void*base-待排序数组首地址size_t num-数组中待排序元素数量size_t width-各元素的占用空间大小int(__cdecl*compare)(const void*,const void*)-指向比较两个元素的函数的指针
qsort函数的用法
#include stdio.h /* printf */
#include stdlib.h /* qsort */int compare (const void * a, const void * b)
{return ( *(int*)a - *(int*)b );
}int main ()
{int n;int values[] { 40, 10, 100, 90, 20, 25 };qsort (values, 6, sizeof(int), compare);for (n0; n6; n)printf (%d ,values[n]);system(pause);return 0;
} 例子2
#include stdio.h /* printf */
#include stdlib.h /* qsort */int compare(const void * a, const void * b)
{return (*(int*)a - *(int*)b);
}int main()
{char s[3][4] { z,g,c }; //字符串数组排序 qsort(s, 3, sizeof(s[0]), compare); //sizeof(s[0])sizeof(char)for (int i 0; i3; i)printf(%s\n, s[i]);system(pause);return 0;
} 模拟实现qsort
#include stdio.h
#include assert.h
#include stdlib.h/*
判断n1,n2元素大小n1比n2大返回正数小返回负数相同返回0
*/
int cmp(const void*n1, const void*n2)
{return *(char*)n1 - *(char*)n2; //升序
}/*
交换每个字节
sizeof(char) 1;sizeof(int ) 4;
sizeof(arr1[0])1;sizeof(arr[0])4;
*/
void Swap(char *buf1, char* buf2, int width)
{int i 0;for (i 0; i width; i){char tmp *buf1;*buf1 *buf2;*buf2 tmp;buf1;buf2;}
}/*
冒泡排序法
*/
void bubble_sort(void *base, int sz, int width, int(*cmp)(const void* n1, const void*n2)) //模拟实现qsort
{int i 0;for (i 0; i sz - 1; i){int j 0;for (j 0; j sz - 1 - i; j){int ret cmp(((char*)base (j*width)), ((char*)base (j 1)*width));if (ret0){Swap(((char*)base (j*width)), ((char*)base (j 1)*width), width);}}}
}int main()
{int i 0;int arr[] { 1, 4, 7, 5, 6, 9 };bubble_sort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), cmp);for (i 0; i sizeof(arr) / sizeof(arr[0]); i){printf(%d , arr[i]);}printf(\n);/*printf输出格式%s*/char arr1[] { a,f,y,w,b };bubble_sort(arr1, sizeof(arr1) / sizeof(arr1[0]), sizeof(arr1[0]), cmp);for (i 0; i sizeof(arr1) / sizeof(arr1[0]); i){printf(%c , arr1[i]);}printf(\n);system(pause);return 0;
}