掌握了冒泡法的人可能一遇到按大小顺序排序的题,觉得用冒泡法思路比较顺手;但当需要排序的数字比较少时,只要逻辑清晰直接比较来得更为简单方便。
冒泡法:
#include <stdio.h> int main() { int a[4]; int i, j, k; printf("please input 3 numbers:"); for (i = 1; i < 4; i++) scanf_s("%d",&a[i]); for (j = 1; j < 3; j++) for (i = 1; i <= 4 - j; i++) if (a[i] < a[i + 1]) { k = a[i + 1]; a[i + 1] = a[i]; a[i] = k; } printf("the sorted numbers:"); for (i = 1; i < 4; i++) printf("%d ", a[i]); printf("\n"); system("pause"); return 0; }
直接比较:#include <stdio.h> int main() { int a = 22; int b = 43; int c = 18; if (a < b) { int tmp = a; a = b; b = tmp; } if (a < c) { int tmp = a; a = c; c = tmp; } if (b < c) { int tmp = b; b = c; c = tmp; } printf("%d %d %d\n", a, b, c); system("pause"); return 0; }