This post was translated from the original with AI assistance. Read the original

Reposted from my old CSDN blog: 三个数的排序常用方法 (written 2017-11-14); formatting tidied during migration.

Problem: say we have three numbers a, b, c; we want to sort them from smallest to largest. What’s the simplest way to do it?


Idea:#

Put the smallest number on the left and the largest on the right. The sorting can be done with three ifs.


Implementation:#

The three-if approach:

//_3if.c
int main(){
	int a,b,c,temp;
	// read in three numbers
	scanf("%d %d %d",&a,&b,&c);
	// three ifs; a table walking through the process follows below
	if(a>b) temp=a,a=b,b=temp;
	if(b>c) temp=b,b=c,c=temp;
	if(a>b) temp=a,a=b,b=temp;
	// print the three sorted numbers
 	printf("%d %d %d",a,b,c);
	return 0;
}

Step-by-step table:#

\abc
Set 1 initial values312
1st if132
2nd if123
3rd if123
Set 2 initial values765
1st if675
2nd if657
3rd if567
Set 3 initial values123
1st if123
2nd if123
3rd if123

Summary:#

As you can see, three passes of if can quickly sort three numbers. This is the fastest and simplest way to sort three numbers. Got it?

Comments


⬆︎TOP