// 判断
int sort_judgeWithMode(int num1, int num2, int mode)
{
return mode? num1<num2:num1>num2;
}
// 起泡排序
/*
mode: 非0:升序, 0:降序
*/
void sort_bubbleSort(int* arr, int len, int mode)
{
int count_exchange, tmp;
do
{
count_exchange = 0;
for(int i = 1; i < len; i ++)
{
if(sort_judgeWithMode(arr[i], arr[i-1], mode))
{
tmp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = tmp;
count_exchange++;
}
}
}while(count_exchange);
}
运行结果
测试代码
#define N 10
int main()
{
int arr[N] = {1,3,543,234,65,23,4,23,234,87};
printf("\n降序排列结果:");
sort_bubbleSort(arr, N, 0);
for(int i = 0; i < N; i ++) printf("%3d ", arr[i]);
printf("\n\n升序排列结果:");
sort_bubbleSort(arr, N, 1);
for(int i = 0; i < N; i ++) printf("%3d ", arr[i]);
return 0;
}