Sorting Parallel Arrays

Hello,
So I've been working on this program for days. I was finally able to read the text file, but now I'm having trouble sorting arrays. I can sort one array, but the corresponding information (which is stored in three other arrays) won't sort with the array. Any help is greatly appreciated.
here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
.
.
.

int main()
{
    int choice;
    ifstream fin ("students.txt");
    if(fin.is_open())
.
.
.
Last edited on
1
2
3
4
5
6
7
if (first!=i)
{
    	temp=SSN[i];
    	SSN[i] = SSN[first];
    	SSN[first] = temp;
	}
}

I would say that you have to swap the entries in the other arrays as well.
Thanks. That worked.
I have one last question.
I have a void function that outputs the information based on the index, but for some reason the comma is not placed right after the last name is outputted it outputs as:
1
2
3
4
5
6
Garza         ,Cody
James         ,Paul
Lee           ,Sarah
. 
.
.

It needs to be outputted as:
1
2
3
4
5
6
Garza,         Cody
James,         Paul
Lee,           Sarah
.
.
.

Here is my void function
1
2
3
4
5
6
7
8
void printInformation(int SSN[], string fname[], string lname[], double scores [])
{
	...
		cout << left << setw(9) << lname[i] << ",";
		
	...
	
}
Last edited on
Replace line 13 with:

cout << left << setw(10) << lname[i] + ',' ;

Your setw applies to the following output operation, so have that operation include the comma.
Last edited on
OP's problem is still not solved: sorting parallel arrays requires a SWAP function that swaps all the related arrays.

1
2
3
4
5
6
7
void swap( int a, int b )
{
  std::swap( SSN[a], SSN[b] );
  std::swap( fname[a], fname[b] );
  std::swap( lname[a], lname[b] );
  std::swap( scores[a], scores[b] );
}

Now in your various sorting functions, use the new swap() function to do the swaps.

Hope this helps.
I tried it, not sure if I'm doing it correctly.

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

void sortSSN(int SSN[], int size)
{	
	int i, j, first;
	int temp;

    for(i=0; i<size-1;i++)
    {
    	first = i;
    	for(j=i+1; j<size; j++)
    		if(SSN[j]< SSN[first])
    			first=j;
    	if (first!=i)
    	       { 		
		temp=SSN[i];
    		SSN[i] = SSN[first];
    		SSN[first] = temp;
    	
		}
	swap(i, first);
	}
    printInformation(SSN, fname, lname, scores);
    cout << endl;
}
You've got to user your brain now and figure out what 'swap' means and how you are supposed to use it in the sort algorithm. When do you 'swap' something?
Topic archived. No new replies allowed.