Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- sort_four_numbers_with_names_without_arrays_and_loops_v1.c
- A nice way to do small, fixed-size sorts is using a sorting network:
- https://en.wikipedia.org/wiki/Sorting_network
- int tmp;
- if (a > b) { tmp = a; a = b; b = tmp; }
- if (c > d) { tmp = c; c = d; d = tmp; }
- if (a > c) { tmp = a; a = c; c = tmp; }
- if (b > d) { tmp = b; b = d; d = tmp; }
- if (b > c) { tmp = b; b = c; c = tmp; }
- Each line codes a comparison and swap between two elements.
- You can use this page to generate optimal sorting networks for small numbers of inputs.
- http://pages.ripco.net/~jgamble/nw.html
- To sort in reverse order, just flip the > signs to < signs.
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- struct Number_and_name
- {
- int num;
- char name[10];
- };
- // To sort in decrease order, just flip the > signs to < signs.
- void sort_four_numbers_without_arrays_and_loops( struct Number_and_name *a,
- struct Number_and_name *b,
- struct Number_and_name *c,
- struct Number_and_name *d )
- {
- struct Number_and_name tmp;
- if ( (*a).num > (*b).num ) // (*a).num is same as a->num
- {
- tmp = *a;
- *a = *b;
- *b = tmp;
- printf("\n %d %d %d %d \n", (*a).num, (*b).num, (*c).num, (*d).num );
- }
- if ((*c).num > (*d).num)
- {
- tmp = *c;
- *c = *d;
- *d = tmp;
- printf("\n %d %d %d %d \n", (*a).num, (*b).num, (*c).num, (*d).num );
- }
- if ((*a).num > (*c).num)
- {
- tmp = *a;
- *a = *c;
- *c = tmp;
- printf("\n %d %d %d %d \n", (*a).num, (*b).num, (*c).num, (*d).num );
- }
- if ((*b).num > (*d).num)
- {
- tmp = *b;
- *b = *d;
- *d = tmp;
- printf("\n %d %d %d %d \n", (*a).num, (*b).num, (*c).num, (*d).num );
- }
- if ((*b).num > (*c).num)
- {
- tmp = *b;
- *b = *c;
- *c = tmp;
- printf("\n %d %d %d %d \n", (*a).num, (*b).num, (*c).num, (*d).num );
- }
- }
- int main(void)
- {
- struct Number_and_name a, b, c, d;
- a.num = 4;
- sprintf( a.name, "first" );
- b.num = 3;
- sprintf( b.name, "second" );
- c.num = 2;
- sprintf( c.name, "third" );
- d.num = 1;
- sprintf( d.name, "fourth" );
- printf("\n a \t b \t c \t d \n %d \t %d \t %d \t %d \n %s %s %s %s \n",
- a.num, b.num, c.num, d.num,
- a.name, b.name, c.name, d.name );
- sort_four_numbers_without_arrays_and_loops( &a, &b, &c, &d );
- printf("\n a \t b \t c \t d \n %d \t %d \t %d \t %d \n %s %s %s %s \n",
- a.num, b.num, c.num, d.num,
- a.name, b.name, c.name, d.name );
- return 0;
- } // main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement