Temperatures Practice Solution

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

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

#define NUM_CITIES 10

// globally defined ~ cities and temperatures in "parellel arrays"
string cities[] = {"Austin", "Boston", "Chicago", "Denver", "Las Vegas", "Los Angeles", "Miami", "New York", "Phoenix", "San Francisco"};
int temps[] = {97, 82, 85, 90, 105, 82, 97, 85, 107, 66};

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

// globally defined ~ array of organized structs to more safely store our cities and temps data
organized weather[NUM_CITIES];

void load_data(void);
void sort_cities(void);
int find_max(int start_index);

int main(void)
{
    load_data();

    sort_cities();

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

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

void load_data(void)
{
    // TODO: load data from cities and temps arrays into weather array
    // loop over each element in my parallel arrays
    for (int i = 0; i < NUM_CITIES; i++)
    {
        // copy cities[i], temperatures[i] into array of structs weather[i]
        weather[i].city = cities[i];
        weather[i].temp = temps[i];
    }
}

// TODO: Sort cities by temperature in descending order - max to min
void sort_cities(void)
{
    // TODO: selection sort weather array by temperature
    for (int i = 0; i < NUM_CITIES - 1; i++)
    {
        // find index of max temperature element
        int max_index = find_max(i);

        // swap max_index element and ith element

        // make a copy of weather[i]
        organized tmp = weather[i];

        // overwrite weather[i]
        weather[i] = weather[max_index];

        // overwrite weather[max_index]
        weather[max_index] = tmp;
    }
}

// Helper Function for sort_cities!
int find_max(int start_index)
{
    // TODO: return index where we find the max temperature in weather array
    int max_index = start_index;
    for (int i = start_index; i < NUM_CITIES; i++)
    {
        if (weather[i].temp > weather[max_index].temp)
        {
            max_index = i;
        }
    }
    return max_index;
}