/*
* PLANETS1 -- sort and print planets in increasing order of diameter
* this uses parallel arrays to hold names and diameters
*
* Usage: planets1
*
* Inputs: none
* Outputs: prints the sorted list
*
* Written by Matt Bishop for ECS 30
* version 1 November 18, 2015
*/
#include <stdio.h>
/*
* arrays of planet names and diameters
* NOTE -- the index for each diameter *must*
* match the index for that planet, so if the
* IAU promotes Ceres, be sure you put both the
* name *and* diameter in the fifth position
* (fourth for zero-based counting), after Mars
* but before Jupiter, of their respective
* arrays
*/
char *names[] = { /* planet names */
"Mercury",
"Venus",
"Earth",
"Mars",
"Jupiter",
"Saturn",
"Uranus",
"Neptune",
"Pluto",
};
/* number of entries */
int sz_names = sizeof(names) / sizeof(char *);
int diameters[] = { /* planet diameters */
4780, /* Mercury */
12104, /* Venus */
12756, /* Earth */
6780, /* Mars */
139822, /* Jupiter */
116464, /* Saturn */
50724, /* Uranus */
49248, /* Neptune */
2400, /* Pluto */
};
/* number of entries */
int sz_diameters = sizeof(diameters) / sizeof(int);
/*
* main routine
*/
int main(void)
{
char *tmp_names; /* temporary to hold name pointer in swap */
int tmp_diameters; /* temporary to hold diameter 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_diameters; 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_diameters; j++)
if (diameters[j] < diameters[min])
min = j;
/*
* if we found a new minimum -- swap
* note we have to swap names too
*/
if (min != i){
/* diameter first */
tmp_diameters = diameters[min];
diameters[min] = diameters[i];
diameters[i] = tmp_diameters;
/* then name */
tmp_names = names[min];
names[min] = names[i];
names[i] = tmp_names;
}
}
/*
* 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_diameters; i++)
printf("%7dkm %s\n", diameters[i], names[i]);
/*
* all done!
*/
return(0);
}
|
ECS 36A, Programming & Problem Solving Version of April 2, 2024 at 12:13PM
|
You can get the raw source code here. |