# sort_four_numbers_without_arrays_and_loops_v1.c

Nov 12th, 2020
653
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /*
2.
3.     sort_four_numbers_without_arrays_and_loops_v1.c
4.
5. A nice way to do small, fixed-size sorts is using a sorting network:
6. https://en.wikipedia.org/wiki/Sorting_network
7.
8. int tmp;
9. if (a > b) { tmp = a; a = b; b = tmp; }
10. if (c > d) { tmp = c; c = d; d = tmp; }
11. if (a > c) { tmp = a; a = c; c = tmp; }
12. if (b > d) { tmp = b; b = d; d = tmp; }
13. if (b > c) { tmp = b; b = c; c = tmp; }
14.
15. Each line codes a comparison and swap between two elements.
16. You can use this page to generate optimal sorting networks for small numbers of inputs.
17. http://pages.ripco.net/~jgamble/nw.html
18. To sort in reverse order, just flip the > signs to < signs.
19.
20.
21.     You can find all my C programs at Dragan Milicev's pastebin:
22.
23.     https://pastebin.com/u/dmilicev
24.
25. */
26.
27. #include <stdio.h>
28.
29. // To sort in decrease order, just flip the > signs to < signs.
30. void sort_four_numbers_without_arrays_and_loops( int *a, int *b, int *c, int *d )
31. {
32.     int tmp;
33.
34.     if (*a > *b) { tmp = *a; *a = *b; *b = tmp; }
35.     if (*c > *d) { tmp = *c; *c = *d; *d = tmp; }
36.     if (*a > *c) { tmp = *a; *a = *c; *c = tmp; }
37.     if (*b > *d) { tmp = *b; *b = *d; *d = tmp; }
38.     if (*b > *c) { tmp = *b; *b = *c; *c = tmp; }
39. }
40.
41. int main(void)
42. {
43.     int a=2, b=1, c=4, d=3;
44.
45.     printf("\n a  b  c  d \n %d  %d  %d  %d \n", a, b, c, d );
46.
47.     sort_four_numbers_without_arrays_and_loops( &a, &b, &c, &d );
48.
49.     printf("\n a  b  c  d \n %d  %d  %d  %d \n", a, b, c, d );
50.
51.
52.     return 0;
53.
54. } // main()
55.