-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemps.c
114 lines (86 loc) · 2.06 KB
/
temps.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// 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)
{
// Add your code here
// bubble sort
while (true)
{
bool swapped = false;
for (int i = 0; i < NUM_CITIES - 1; i++)
{
if (temps[i].temp > temps[i + 1].temp)
{
avg_temp tmp = temps[i];
temps[i] = temps[i + 1];
temps[i + 1] = tmp;
swapped = true;
}
}
if (!swapped)
{
return;
}
}
// selection sort
// for (int i = 0; i < NUM_CITIES - 1; i++)
// {
// int min = temps[i].temp;
// int idx = i;
// for (int j = i + 1; j < NUM_CITIES; j++)
// {
// if (min > temps[j].temp)
// {
// min = temps[j].temp;
// idx = j;
// }
// }
// if (i != idx)
// {
// avg_temp tmp = temps[i];
// temps[i] = temps[idx];
// temps[idx] = tmp;
// }
// }
}