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 (n=0; n<6; 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; i<3; 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 (ret>0){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;
}