Index sorting within loop

I am supposed to write a program that let the user enter the amount of students => enter the height of the students => sort the height accordingly, female first (with even indexes: 2 4 6 8 etc) and then male (indexes 1 3 5 7 etc)
Problem is if some students' heights are the same, sometimes my program put the latter index first
(ex: 3 158cm people with index 1+3+9, the program sorts it as 9-3-1) and I have to do the opposite.
I'm not sure what should I do to sort those, here's my code so far:

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
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    int stuNum;
    cin >> stuNum;
    int height[stuNum], ind[stuNum];

    for (int i = 0; i < stuNum; i++)
    {
        cin >> height[i];
    }

    for (int i = 0; i < stuNum; i++)
    {
        ind[i] = i+1;
    }

    for (int i = 0; i < stuNum-1; i++)
    {
        for (int j = i+1; j < stuNum; j++)
        {
            if (height[i] > height[j])
            {
                swap(height[i], height[j]);
                swap(ind[i], ind[j]);
               
            }
        }
    }

    for (int i = 0; i < stuNum; i++)
    {
        if (ind[i]%2 == 0)
        {
            cout << ind[i] << " ";
        }
    }

    for (int i = 0; i < stuNum; i++)
    {
        if (ind[i]%2 != 0)
        {
            cout << ind[i] << " ";
        }
    }

    return 0;

}


Any help would be appreciated greatly!
the thing you seek is called a stable sort, which leaves items with the same value in their original relative order. It requires more logic and is slower than a normal sort that can put them in any order. You can look into this online, its a bit to go into here.

OR, if you just want to keep the boys & girls in even/odd setup, you can split the data into 2 arrays, sort both, and merge back together afterwards, such that the boys are sorted, and the girls are sorted, but the boys and girls together are not assured to be sorted. not sure if this is what you are asking.
Last edited on
@jonnin thank you so much, i really appreciate your help!
Topic archived. No new replies allowed.