How can I sort one array and keep another in sync?

I need to know how to write a simple linear(insertion) sort that sort's an array of #'s into descending order while maintaining the link up of another array of numbers.

For example, a set of data for array ID will look like this:
ID[25]={ 4, 2, 1, 5, 3}

And a set of data for array SAT will look like this:
SAT[25]={ 780, 600, 1900, 690, 1200}

PS: ALL OF THESE NUMBERS ARE COMING FROM A DATA FILE

I need it too look something like this:

ID: SAT Score:
5 690
4 780
3 1200
2 600
1 1900

Can someone show me please?
When you are making swapping of first array elements, swap also corresponding elements of the second array.
Is it a proper solution?
Well here is my code to sort 1 of the arrays.

1
2
3
4
5
6
7
8
9
10
11
12
int lsort(int n, ID[], scores[]){
     for(int pass=0; pass<n-1; pass++){
          for(int cand=pass+1; cand<n; cand++){
               if(ID[cand]<ID[pass}{
                    temp=ID[cand];
                    ID[cand]=ID[pass];
                    ID[pass]=temp;
                    }
          }
     }
return;
}


The thing is I am absolutely lost on making the other array sync with it like my example above.
I sort of understand your concept but I don't know how to write that out in code.

Am I supposed to write another insertion sort for the second array?
Last edited on
Here
1
2
3
          temp=ID[cand];
                    ID[cand]=ID[pass];
                    ID[pass]=temp;

you swap ID[cand] and ID[pass]. You also can swap here content of the second array (with the same indexes).
If you are swapping contents of both arrays simultaneously it is equivalent that your arrays are linked.
so would this be the correct way?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//lsort
int lsort(int n, ID[], scores[]){
     for(int pass=0; pass<n-1; pass++){
          for(int cand=pass+1; cand<n; cand++){
               if(ID[cand]<ID[pass]}{
                    temp=ID[cand];
                    temp2=scores[cand]
                    ID[cand]=ID[pass];
                    scores[cand]=scores[pass]
                    ID[pass]=temp2;
                    ID[pass]=temp;
                    }
          }
     }
return;
}  
You will need to include this line of code:

#include <iomanip>

Ok, here we go:

1
2
3
4
5
6
7
8
9
10
11
12
 
cout << fixed;
cout << left;
cout << setw(10) << "ID" << setw(10) << "SAT" << endl;
cout << setw(10) << "--------- " << setw(10) << "----------" << endl;
for(int i=25;i>=0;i--){
for(int w = 25;w>0;w--){
if(ID[i] == w){
cout << setw(10) << ID[i] << setw(10) << SAT[i] << endl;
}
}
}


You might have to tweak it a bit, because I did not test it. Also, it will not sort the array, it will just display them.
Last edited on
Yes, it is almost correct. Should be (lines 9-11):
1
2
3
                    scores[cand]=scores[pass];
                    ID[pass]=temp;
                    scores[pass]=temp2;

Topic archived. No new replies allowed.