代码块:
方法1:(交换指针变量指向的值)
#include
int main()
{
int a, b, c, *i, *j, *k;
i=&a, j=&b, k=&c;
printf("Please enter a, b, c: ");
scanf("%d %d %d", i, j, k);
if (*i<*j){
if (*j<*k) printf("%d %d %d\n", *i, *j, *k);
else{
if (*i<*k) printf("%d %d %d\n", *i, *k, *j);
else printf("%d %d %d\n", *k, *i, *j);
}
}
else{
if (*j>*k) printf("%d %d %d\n", *k, *j, *i);
else{
if (*i<*k) printf("%d %d %d\n", *j, *i, *k);
else printf("%d %d %d\n", *j, *k, *i);
}
}
return 0;
}
方法2:(交换指针变量)
#include
int main()
{
int a, b, c, *i, *j, *k, t;
i=&a, j=&b, k=&c;
printf("Please enter a, b, c: ");
scanf("%d %d %d", i, j, k);
if (*i<*j){
if (*j>*k){
if (*i<*k) t=*j, *j=*k, *k=t;
else{
t=*i, *i=*k, *k=t;
t=*j, *j=*k, *k=t;
}
}
}
else{
if (*j>*k) t=*i, *i=*k, *k=t;
else{
if (*i<*k) t=*i, *i=*j, *j=t;
else{
t=*i, *i=*j, *j=t;
t=*j, *j=*k, *k=t;
}
}
}
printf("%d %d %d\n", a, b, c);
return 0;
}
方法3:(利用函数的模块化设计)
#include
void sort(int *x, int *y, int *z);
int main()
{
int a, b, c, *i, *j, *k;
i=&a, j=&b, k=&c;
printf("Please enter a, b, c: ");
scanf("%d %d %d", i, j, k);
sort(i, j, k);
printf("%d %d %d\n", a, b, c);
return 0;
}
void sort(int *x, int *y, int *z)
{
int t;
if (*x<*y){
if (*y>*z){
if (*x<*z) t=*y, *y=*z, *z=t;
else{
t=*x, *x=*z, *z=t;
t=*y, *y=*z, *z=t;
}
}
}
else{
if (*y>*z) t=*x, *x=*z, *z=t;
else{
if (*x<*z) t=*x, *x=*y, *y=t;
else{
t=*x, *x=*y, *y=t;
t=*y, *y=*z, *z=t;
}
}
}
}
方法4:(利用数组)
#include
int main()
{
int a[3], *p, i, j, t;
for (p=a, printf("Please enter 3 number: "); p3; scanf("%d", p++));
for (i=0; i<3; i++)
for (j=i+1; j<3; a[i]>a[j] ? t=a[i], a[i]=a[j], a[j++]=t : j++);
for (p=a; p3; printf("%d ", *p++));
printf("\n");
return 0;
}
方法5:(利用数组-2)
#include
int main()
{
int a[3], *p, *i, *j, t;
for (p=a, printf("Please enter 3 number: "); p3; scanf("%d", p++));
for (i=a; i3; i++)
for (j=i+1; j3; *i>*j ? t=*i, *i=*j, *j=t, j++ : j++);
for (p=a; p3; printf("%d ", *p++));
printf("\n");
return 0;
}
方法6:(利用数组和函数的模块化设计)
#include
void sort(int *s, int n);
int main()
{
int a[3], *p;
for (p=a, printf("Please enter 3 number: "); p3; scanf("%d", p++));
sort(a, 3);
for (p=a; p3; printf("%d ", *p++));
printf("\n");
return 0;
}
void sort(int *s, int n)
{
int *i, *j, t;
for (i=s; i<s+n; i++)
for (j=i+1; j<s+n; *i>*j ? t=*i, *i=*j, *j=t, j++ : j++);
}
方法7:(利用动态内存分配)
#include
#include
void input(int *p_num, int n);
void sort(int *p_num, int n);
void print(int *p_num, int n);
int main()
{
int *num;
num=(int *)malloc(3*sizeof(int));
input(num, 3);
sort(num, 3);
print(num, 3);
system("pause");
return 0;
}
void input(int *p_num, int n)
{
int *p;
for (p=p_num, printf("Please enter %d numbers: ", n); p"%d", p++));
}
void sort(int *p_num, int n)
{
int *i, *j, temp;
for (i=p_num; ifor (j=i+1; j*i>*j ? temp=*i, *i=*j, *j=temp, j++ : j++);
}
void print(int *p_num, int n)
{
int *p;
for (p=p_num, printf("Sort by; "); pprintf("%d ", *p++));
printf("\n");
}