介绍
冒泡排序是一种简单的排序算法,它重复地遍历要排序的数列,一次比较两个元素,如果顺序错误就把它们交换过来。遍历数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
- 比较相邻的元素,如果它们的顺序错误就把它们交换过来。
- 对每一对相邻元素进行比较,如果它们的顺序错误就交换它们。
- 重复步骤 2,直到没有再需要交换,也就是说该数列已经排序完成。
第一轮排序完成,最大数9到达数组末尾,继续进行遍历比较,直到所有数按正确顺序排列
代码实现
#define PTR_MATH(base,i,width) ( ((char*)base) + (i)*width )
PTR_MATH
函数用于计算指针偏移量。
//冒泡排序
void bubbleSort(void* base, int len,int width, int(*compare)(const void* e1, const void* e2)){
if(base==NULL||compare == NULL||width<=0||len<=1)
return;
void* temp = malloc(width);
if(temp == NULL)
return;
for(int i = 0; i < len; i++){
for(int j = 0; j < len - i - 1; j++){
if(compare(PTR_MATH(base,j,width), PTR_MATH(base,j+1,width)) > 0){
lSwap(PTR_MATH(base,j,width), PTR_MATH(base,j+1,width),temp,width);
}
}
}
free(temp);
}
//交换两段内存的数据
void lSwap(void* e1, void* e2, void* temp, int width){
if(width<=0)
return;
void* temp_ = NULL;
if(temp==NULL){
temp_ = (void*)malloc(width);
}else{
temp_ = temp;
}
memcpy(temp_, e1, width);
memcpy(e1, e2, width);
memcpy(e2, temp_, width);
if(temp==NULL)
free(temp_);
}
参数介绍
void bubbleSort(void* base, int len,int width, int(*compare)(const void* e1, const void* e2));
void* base
: 指向要排序数组的指针。int len
: 数组的长度。int width
: 数组中每个元素的大小。int(*compare)(const void* e1, const void* e2)
: 一个比较函数,用于比较两个元素的大小。
总结
冒泡排序的时间复杂度为 O(n^2),空间复杂度为 O(1)。当数据量较大时,冒泡排序的效率较低。