【C】排序算法之冒泡排序

目录

1. 算法基本思想

2. 源代码

2.1 整型数字排序

2.2 输入输出函数及主函数

2.3 字符串排序

2.4 通用冒泡排序

3. 输出结果

3.1 整型数字排序

3.2 字符串排序

3.3 通用冒泡排序


1. 算法基本思想

以升序为例:

  • 比较相邻的两个数字,若前者大于后者,则交换两个数字的顺序,反之则不交换;(ps:交换两个数字的顺序
  • 重复上述操作,直到最大的数字 沉 入最右边,最小的数字 在最左边为止。

假如有 N 个数字排序,那么需要比较 N - 1 趟,在每一趟的比较中,比较次数有所不同,第 i 趟比较需要比较 N - 1 - i 次。

2. 源代码

2.1 整型数字排序

void BubbleSort(int *a, int len) {
	int i = 0;
	int j = 0;

	assert(NULL != a);

	for (i = 0; i < len - 1; i++) {
		for (j = 0; j < len - i - 1; j++) {
			if (a[j] > a[j + 1]) {
				a[j] = a[j] ^ a[j + 1];
				a[j + 1] = a[j] ^ a[j + 1];
				a[j] = a[j] ^ a[j + 1];
			}
		}
	}

	return;
}

不足:即使所给数字是有序的,上述算法仍会对其进行一趟又一趟的比较,这样效率太低。

改进:考虑设置一个标志位,假如在某一趟比较中没有发生任何数字的交换,那么说明此刻已经是一个有序的序列,不需要再进行比较了。

首先设置一个标志位 flag = 1,每次进入循环后先把 flag 置 0,假如发生了数字交换,再把 flag 置 1,最后判断 flag 的值,假如为 0 则结束循环。

void BubbleSort(int *a, int len) {
	int i = 0;
	int j = 0;
	int flag = 1;

	assert(NULL != a);

	while (flag) {
		flag = 0;

		for (i = 0; i < len - 1; i++) {
			for (j = 0; j < len - i - 1; j++) {
				if (a[j] > a[j + 1]) {
					a[j] = a[j] ^ a[j + 1];
					a[j + 1] = a[j] ^ a[j + 1];
					a[j] = a[j] ^ a[j + 1];
					flag = 1;
				}
			}
		}

		if (0 == flag)
			break;
	}

	return;
}

不足:代码繁琐,多次判断 flag 。

改进:考虑在外层循环中同时判断 flag 以及外层循环变量。

void BubbleSort(int *a, int len) {
	int i = 0;
	int j = 0;
	int flag = 1;

	assert(NULL != a);

	for (i = 0; (flag) && (i < len - 1); i++) {
		for (j = 0; j < len - i - 1; j++) {
			flag = 0;

			if (a[j] > a[j + 1]) {
				a[j] = a[j] ^ a[j + 1];
				a[j + 1] = a[j] ^ a[j + 1];
				a[j] = a[j] ^ a[j + 1];
				flag = 1;
			}
		}
	}

	return;
}

当然,也可以使用指针来实现冒泡排序。

void BubbleSort(int *pArr, int len) {
	int *left = pArr;
	int *right = pArr + len - 1;
	int *current = pArr;
	int flag = 1;

	assert(NULL != pArr);

	for (left = pArr; (left < right) && (flag); right--) {
		flag = 0;

		for (current = pArr; current < right; current++) {
			if (*current > *(current + 1)) {
				*current = (*current) ^ (*(current + 1));
				*(current + 1) = (*current) ^ (*(current + 1));
				*current = (*current) ^ (*(current + 1));
				flag = 1;
			}
		}
	}

	return;
}

2.2 输入输出函数及主函数

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define ARRAY_LEN 4

void Input(int *pNum, int length) {
	int k = 0;

	if ((NULL != pNum) && (length > 0)) {
		for (k = 0; k < length; k++) {
			printf("请输入第%d个数字:", k+1);
			scanf("%d", &pNum[k]);
		}
	} else {
		exit(1);
	}
	
	return;
}

void Output(int *p, int le) {
    int m = 0;
    if ((NULL != p) && (le > 0)) {
        for (m = 0; m < le; m++) {
            printf("%d ", p[m]);
        }
    } else {
        exit(1);
    }

    printf("\n");

    return;
}

int main(void) {
	int arr[ARRAY_LEN] = {0};
	
	Input(arr, ARRAY_LEN);

	printf("排序之前的数字分别是:\n");
	Output(arr, ARRAY_LEN);

	printf("排序之后的数字分别是:\n");
	BubbleSort(arr, ARRAY_LEN);
	Output(arr, ARRAY_LEN);

	return 0;
}

2.3 字符串排序

#include <stdio.h>
#include <string.h>
#include <assert.h>

void StringBubbleSort(char **str, int len) {
    int i = 0;
    int flag = 1;

    assert((NULL != str));

    for (i = 0; (i < len - 1) && (flag); i++) {
        int j = 0;
        flag = 0;

        for (j = 0; j < len - 1 - i; j++) {
            if (strcmp(str[j], str[j + 1]) > 0) {
                char * tmp = str[j];
                str[j] = str[j + 1];
                str[j + 1] = tmp;
                flag = 1;
            }
        }
    }

    return;
}

void OutputStr(char **str, int len) {
    int i = 0;
    assert((NULL != str));

    for (i = 0; i < len; i++) {
        printf("%s ", str[i]);
    }

    printf("\n");

    return;
}

int main(void) {
	char *str[] = {"the","world","change"};
	int len = sizeof(str) / sizeof(char *);

	printf("before: ");
	OutputStr(str, len);
	StringBubbleSort(str, len);
	printf("after: ");
	OutputStr(str, len);

	return 0;
}

2.4 通用冒泡排序

void Swap(char *s1, char *s2, int width) {
	int i = 0;

	assert((NULL != s1) && (NULL != s2));

	for (i = 0; i < width; i++) {
		char tmp = *s1;
		*s1 = *s2;
		*s2 = tmp;
		s1++;
		s2++;
	}

	return;	
}

void CommonBubbleSort(void * base, int len, int width, 
                        int (*cmp)(const void * e1, const void * e2)) {
	int i = 0;
	int j = 0;

	assert((NULL != base) && (NULL != cmp));

	for (i = 0; i < len - 1; i++) {
		for (j = 0; j < len - i - 1; j++) {
			if (cmp((char *)base + width * j, (char *)base + width * (j + 1)) > 0) {
				Swap((char *)base + width * j, (char *)base + width * (j + 1), width);
			}
		}
	}

	return;
}

接下来以排序结构体中的姓名为例,

#include <stdio.h>
#include <assert.h>
#include <string.h>

struct Student {
	char name[20];
	int age;
};

int CmpStructName(const void *e1, const void *e2) {
	assert((NULL != e1) && (NULL != e2));

	return strcmp(((struct Student *)e1)->name, ((struct Student *)e2)->name);
}

void PrintStructData(struct Student stu[], int len) {
	int i = 0;

	for (i = 0; i < len; i++) {
		printf("name = %s, age = %d\n", stu[i].name, stu[i].age);
	}

	printf("\n");

	return;
}

int main(void) {
	struct Student stu[3] = {{"zhangsan", 20}, {"lisi", 15}, {"wangwu", 30}};
	int len = sizeof(stu) / sizeof(struct Student);

	// 对结构体中的名字进行排序
	printf("before:\n");
	PrintStructData(stu, len);
	CommonBubbleSort(stu, len, sizeof(struct Student), CmpStructName);
	printf("after:\n");
	PrintStructData(stu, len);

	return 0;
}

3. 输出结果

3.1 整型数字排序

3.2 字符串排序

3.3 通用冒泡排序

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值