1、三个值升序
#include <stdio.h> void swap(int *x, int *y) { int tmp = *x; *x = *y; *y = tmp; } void sort(int *i, int *j, int *k) { if(*i > *j) swap(i, j); if(*i > *k) swap(i, k); if(*j > *k) swap(j, k); } int main(void) { int a, b, c; puts("please input three integers."); printf("a = "); scanf("%d", &a); printf("b = "); scanf("%d", &b); printf("c = "); scanf("%d", &c); sort(&a,&b,&c); puts(" ========================="); printf("a = %d | b = %d | c = %d ", a, b, c); return 0; }
2、三个值降序
#include <stdio.h> void swap2(int *x, int *y) { int tmp = *x; *x = *y; *y = tmp; } int sort2(int *n1, int *n2, int *n3) { if(*n1 < *n2) swap2(n1, n2); if(*n1 < *n3) swap2(n1, n3); if(*n2 < *n3) swap2(n2, n3); } int main(void) { int a, b, c; puts("please input three integers."); printf("a = "); scanf("%d", &a); printf("b = "); scanf("%d", &b); printf("c = "); scanf("%d", &c); sort2(&a, &b, &c); puts(" =========================="); printf("a = %d | b = %d | c = %d ", a, b, c); return 0; }
3、对数组的元素进行升序排列
#include <stdio.h> #define NUMBER 6 void swap(int *x, int *y) { int tmp = *x; *x = *y; *y = tmp; } void sort(int x[], int n) { int i, j; for(i = 0; i < n - 1; i++) { for(j = n - 1; j > i; j--) { if(x[j - 1] > x[j]) { swap(&x[j - 1], &x[j]); // 此处的函数调用给与的实参需要使用取址运算符&,因为x[j-i]和x[j]为数组元素,需要获得指向元素的指针,使用取址运算符&+对象,获得地址, //生成指针。 } } } } int main(void) { int i, a[NUMBER]; puts("please input the element of the array."); for(i = 0; i < NUMBER; i++) { printf("NO.%d = ", i + 1); scanf("%d", &a[i]); } sort(a, NUMBER); puts(" ======================"); for(i = 0; i < NUMBER; i++) { printf("a[%d] = %d ", i, a[i]); } return 0; }