#include <stdio.h>
// 定义一个宏,用于交换两个变量的值
#define SWAP(type, a, b) do { type temp = a; a = b; b = temp; } while (0)
// 定义一个宏,实现冒泡排序
#define BUBBLE_SORT(type, arr, size) do { \
int i, j; \
for (i = 0; i < size - 1; i++) { \
for (j = 0; j < size - i - 1; j++) { \
if (arr[j] > arr[j + 1]) { \
SWAP(type, arr[j], arr[j + 1]); \
} \
} \
} \
} while (0)
int main() {
int intArr[] = {5, 4, 3, 2, 1};
float floatArr[] = {5.5, 4.4, 3.3, 2.2, 1.1};
int intSize = sizeof(intArr) / sizeof(intArr[0]);
float floatSize = sizeof(floatArr) / sizeof(floatArr[0]);
BUBBLE_SORT(int, intArr, intSize);
BUBBLE_SORT(float, floatArr, floatSize);
printf("Sorted int array: ");
for (int i = 0; i < intSize; i++) {
printf("%d ", intArr[i]);
}
printf("\n");
printf("Sorted float array: ");
for (int i = 0; i < floatSize; i++) {
printf("%f ", floatArr[i]);
}
printf("\n");
return 0;
}
SWAP
宏:
- 这个宏用于交换两个同类型变量的值。
do { ... } while (0)
结构保证了宏在复杂表达式中使用时,不会出现意外的语法错误。
BUBBLE_SORT
宏:
- 实现了冒泡排序的逻辑。
- 通过两个嵌套的
for
循环遍历数组,比较相邻元素,如果顺序错误则调用SWAP
宏交换它们。
- 这里
type
是数组元素的类型,arr
是数组名,size
是数组的大小。
main
函数:
- 定义了一个
int
类型数组和一个float
类型数组。
- 计算数组的大小,并分别调用
BUBBLE_SORT
宏对两个数组进行排序。
- 最后打印排序后的数组。