/* * PLANETS2 -- sort and print planets in increasing order of diameter * this uses structures to hold names and diameters * * Usage: planets2 * * Inputs: none * Outputs: prints the sorted list * * Written by Matt Bishop for ECS 30 * version 1 November 18, 2015 */ #include /* * structure that holds planet name and diameter */ struct celestial { char *name; /* name of planet */ int diameter; /* diameter of planet */ }; /* define a type to make things easier */ typedef struct celestial PLANET; /* * array of planet names and diameters * note these are kept together, so we don't * have to worry about keeping two lists * synchronized */ PLANET planets[] = { { "Mercury", 4780, }, { "Venus", 12104, }, { "Earth", 12756, }, { "Mars", 6780, }, { "Jupiter", 139822, }, { "Saturn", 116464, }, { "Uranus", 50724, }, { "Neptune", 49248, }, { "Pluto", 2400, }, }; /* number of entries */ int sz_planets = sizeof(planets) / sizeof(PLANET); /* * main routine */ int main(void) { PLANET tmp_planets; /* temporary to hold structure in swap */ int i, j; /* counters in for loops */ int min; /* index of minimum diameter this pass */ /* * do selection sort * make repeated passes through the list, * putting the planet with the minimum diameter in the * first position, and then sorting the rest of the list */ for(i = 0; i < sz_planets; i++){ /* assume first one is minimum diameter */ min = i; /* * now find out if it *really* is the minimum * if not, swap it with the minimum and continue */ for(j = i + 1; j < sz_planets; j++) if (planets[j].diameter < planets[min].diameter) min = j; /* * if we found a new minimum -- swap */ if (min != i){ tmp_planets = planets[min]; planets[min] = planets[i]; planets[i] = tmp_planets; } } /* * now print out the planets and diameters * in increasing order of diameter */ printf("Planets in order of size of diameters:\n"); for(i = 0; i < sz_planets; i++) printf("%7dkm %s\n", planets[i].diameter, planets[i].name); /* * all done! */ return(0); }