Advertisement
dmilicev

sort_four_numbers_without_arrays_and_loops_v2.c

Nov 12th, 2020
807
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. /*
  2.  
  3.     sort_four_numbers_without_arrays_and_loops_v2.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; printf("\n %d  %d  %d  %d \n", *a, *b, *c, *d ); }
  35.     if (*c > *d) { tmp = *c; *c = *d; *d = tmp; printf("\n %d  %d  %d  %d \n", *a, *b, *c, *d ); }
  36.     if (*a > *c) { tmp = *a; *a = *c; *c = tmp; printf("\n %d  %d  %d  %d \n", *a, *b, *c, *d ); }
  37.     if (*b > *d) { tmp = *b; *b = *d; *d = tmp; printf("\n %d  %d  %d  %d \n", *a, *b, *c, *d ); }
  38.     if (*b > *c) { tmp = *b; *b = *c; *c = tmp; printf("\n %d  %d  %d  %d \n", *a, *b, *c, *d ); }
  39. }
  40.  
  41. int main(void)
  42. {
  43. //  int a=2, b=1, c=4, d=3;
  44. //  int a=4, b=2, c=1, d=3;
  45.     int a=4, b=3, c=2, d=1;
  46.  
  47.     printf("\n a  b  c  d \n %d  %d  %d  %d \n", a, b, c, d );
  48.  
  49.     sort_four_numbers_without_arrays_and_loops( &a, &b, &c, &d );
  50.  
  51.     printf("\n a  b  c  d \n %d  %d  %d  %d \n", a, b, c, d );
  52.  
  53.  
  54.     return 0;
  55.  
  56. } // main()
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement