arranging string elements

Nov 27, 2016 at 9:24pm
I'm close to making this work. I'm trying to get the months to be organized with the number they are assigned and arranged by number from highest to lowest.

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
#include <iostream>
#include <string>
using namespace std;

// BRANDON SKAR, 11/26/2016, PROGRAM CHALLENGE 5: RAINFALL STATISTICS MODIFICATION

void selectionSort(double[], int, string[]);

int main()
{
	const int SIZE = 12;
	// ASSIGN EACH MONTH TO AN ELEMENT OF A SINGLE DIMENSION ARRAY
	string months[] = { "January", "February", "March", "April", "May", "June",
						"July", "August", "September", "October", "November", "December" };
	double rainfall[SIZE];
	// LOOP FOR ENTERING RAINFALL FOR EACH MONTH
	for (int i = 0; i < SIZE; i++)
	{
		cout << "Enter rainfall for month of " << months[i] << ": ";
		cin >> rainfall[i];
	}
	// FUNCTION FOR SORTING RAINFALL FROM HIGHEST TO LOWEST
	selectionSort(rainfall, SIZE, months);

	for (int i = 0; i < SIZE; i++)
		cout << months[i] << ":  " << rainfall[i] << endl;

	system("pause");
	return 0;
}

void selectionSort(double array[], int size, string monthArray[])
{
	int maxValue, minIndex;
	string element;
	for (int scan = 0; scan < (size - 1); scan++)
	{
		minIndex = scan;
		maxValue = array[scan];
		for (int i = scan + 1; i < size; i++)
		{
			if (array[i] > maxValue)
			{
				maxValue = array[i];
				element = monthArray[i];
				minIndex = i;
			}
		}
		monthArray[minIndex] = monthArray[scan];
		array[minIndex] = array[scan];
		array[scan] = maxValue;
		monthArray[scan] = element;
	}
}
Nov 27, 2016 at 9:49pm
In many cases 'element' may not have been set before you try to use it in line 52.

Try adding
element = monthArray[scan];
after line 39 and before you start the inner for loop on line 40.

BTW. This is not a very efficient way of sorting - especially if the array is already nearly sorted.
Nov 27, 2016 at 10:01pm
yes that worked. thank you so much. this has been puzzling me for a while now
Topic archived. No new replies allowed.