0

I have two arrays. One is of roll numbers, the other is of total marks for the roll numbers. I have to sort the roll number array in ascending order while keeping the data as it is assigned to each roll number. I have sorted the array but how do I put the marks accordingly to the roll number?

Here's the code so far.

int roll_num[5] = { 2, 4, 1, 6, 8 }, total_marks[5] = { 9, 7, 10, 8, 9 }, min=0, temp, size = 5;
    for (int i = 0; i <= size; i++)
    {
        min = i;
        for (int j = i + 1; j < size; j++)
        {
            if (roll_num[j] < roll_num[min])
            {
                min = j;
            }
        }
        swap(roll_num[i], roll_num[min]);
    }
    cout << "Roll No." << " " << "Total Marks" << endl;
    for (int i = 0; i < size; i++)
    {
        cout << roll_num[i] << "       |     " << total_marks[i] << endl;
    }
scypx
  • 67
  • 7
  • 2
    Consider using one array of a structure that contains both values. This keeps both values together regardless of how you sort. – user4581301 Jan 23 '20 at 16:14
  • 2
    If you're going to insist on using parallel arrays you have to keep them parallel. When you swap two entries in `roll_num` swap the corresponding entries in `total_marks`. – Pete Becker Jan 23 '20 at 16:17
  • Does this answer your question? [Sorting two corresponding arrays](https://stackoverflow.com/questions/3909272/sorting-two-corresponding-arrays) – Borgleader Jan 23 '20 at 16:20
  • @PeteBecker by entries you mean store the indices of those numbers? – scypx Jan 23 '20 at 16:20
  • What's wrong with `std::sort`? – Jesper Juhl Jan 23 '20 at 16:24

2 Answers2

5

You probably want to combine the two arrays into a std::map. Then it will be sorted and your values will be connected:

int roll_num[5] = { 2, 4, 1, 6, 8 };
int total_marks[5] = { 9, 7, 10, 8, 9 };
std::map<int, int> my_map;
for (int i=0; i < 5; ++i) {
    my_map.insert(roll_num[i], total_marks[i]);
}

if you want them sorted by roll_num.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
1

As your basic sort algorithm does work (I checked it), all you need do is add an equivalent swap call for the total_marks array. Thus, immediately after the:

swap(roll_num[i], roll_num[min]);

line, just add this:

swap(total_marks[i], total_marks[min]);

Thus, everything that is done on the roll_num array will be replicated in the total_marks array.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • alright this worked but I really have to dry run this first. Thanks btw!!!! – scypx Jan 23 '20 at 16:25
  • 1
    @scypx With the data given in your code, both your sort algorithm and my suggested addition work! But feel free to test it yourself on other data. – Adrian Mole Jan 23 '20 at 16:26