0

I am trying to use selection sort to sort the list in descending order and I have been on it , just having absolutely no progress. I don't know what to do anymore! This is my latest trial

// Practice working with structs // Practice applying sorting algorithms

#include "cs50.h" #include <stdio.h>

#define NUM_CITIES 10

typedef struct { string city; int temp; } avg_temp;

avg_temp temps[NUM_CITIES];

void sort_cities(void);

int main(void) { temps[0].city = "Austin"; temps[0].temp = 97;

temps[1].city = "Boston";
temps[1].temp = 82;

temps[2].city = "Chicago";
temps[2].temp = 85;

temps[3].city = "Denver";
temps[3].temp = 90;

temps[4].city = "Las Vegas";
temps[4].temp = 105;

temps[5].city = "Los Angeles";
temps[5].temp = 82;

temps[6].city = "Miami";
temps[6].temp = 97;

temps[7].city = "New York";
temps[7].temp = 85;

temps[8].city = "Phoenix";
temps[8].temp = 107;

temps[9].city = "San Francisco";
temps[9].temp = 66;

sort_cities();

printf("\nAverage July Temperatures by City\n\n");

for (int i = 0; i < NUM_CITIES; i++)
{
    printf("%s: %i\n", temps[i].city, temps[i].temp);
}

}

// TODO: Sort cities by temperature in descending order void sort_cities(void) { for(int i =0; i < temps[NUM_CITIES]; i++) { for(int j = i+1; j < temps[i]; j++) { if(temps[NUM_CITIES].temp > temps[i]) { temps[NUM_CITIES].temp = temp[i].temp; } } }

}

1 Answer 1

0

There's just a bunch of typos in your function at the moment, I made it run by fixing them, though the function doesn't do anything yet:

void sort_cities(void)
{
    for (int i = 0; i < NUM_CITIES; i++)
    {
        for (int j = i + 1; j < temps[i].temp; j++)
        {
            if (temps[NUM_CITIES - 1].temp > temps[i].temp)
            {
                temps[NUM_CITIES - 1].temp = temps[i].temp;
            }
        }
    }
}

Make sure you're remembering that lists start at 0, so anytime you're using your global variable NUM_CITIES to go through a list, make sure you're subtracting 1 from it, that way you won't go past the end of the list. (There are 10 cities, but in the list the 10th one is called temps[9].temp and the first one is called temps[0].temp)

Make sure you also remember to swap the names of the cities in the list, to the same place as the corresponding temperature, or else they'll all get mixed up.

Hope this helps!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .