輸入三整數 x,y,z,通過兩兩比較交換使 x≤y≤z:先讓 x 最小(與 y,z 比較交換),再讓 y≤z。
// Created by www.runoob.com on 15/11/9.
// Copyright © 2015年 菜鳥教程. All rights reserved.
//
#include <stdio.h>
int main() {
int x, y, z, t;
printf("\n請輸入三個數字:\n");
scanf("%d%d%d", &x, &y, &z);
if (x > y) { t = x; x = y; y = t; }
if (x > z) { t = z; z = x; x = t; }
if (y > z) { t = y; y = z; z = t; }
printf("從小到大排序: %d %d %d\n", x, y, z);
return 0;
}
請輸入三個數字:
1 3 2
從小到大排序: 1 2 3
三次比較交換確保有序,時間 O(1),適合固定小規模排序。