Let's say we have n
number of houses. This is a house:
struct Casa {
int id;
int membri;
};
I am reading the size of the struct and each struct's membri
from a txt file. The first value is the size of the struct (n
).
5
2
8
6
10
4
I increment the ID when reading from file:
void citire(Casa house[], int n, std::ifstream & file) {
for (int i = 0; i < n; i++)
{
file >> house[i].membri;
house[i].id = i + 1;
}
}
How do I output the houses's ID's in ascending order based on membri
?
For example:
id: 1 - membri: 2
id: 2 - membri: 8
id: 3 - membri: 6
id: 4 - membri: 10
id: 5 - membri: 4
should output:
id: 1 - membri: 2
id: 5 - membri: 4
id: 3 - membri: 6
id: 2 - membri: 8
id: 4 - membri: 10
This is what I've tried and it doesn't work and I can't see why:
void sortareSelectie(int v[], int n) {
int i, j, min, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++) {
if (v[j] < v[min]) min = j;
}
// swap
temp = v[min];
v[min] = v[i];
v[i] = temp;
}
}
void sort(Casa house[], int n) {
int v[10], key[10];
for (int i = 0; i < n; i++) {
v[i] = house[i].membri;
}
sortareSelectie(v, n);
for (int i = 0; i < n; i++) {
std::cout << "Membri: " << v[i] << " - ID: " << house[i].id << std::endl;
}
}
I've seen examples with vectors, with structs, with arrays.
How to obtain the index permutation after the sorting
keeping track of the original indices of an array after sorting in C
Sorting array and saving the old index in C++
Get the indices of an array after sorting?
https://www.geeksforgeeks.org/keep-track-of-previous-indexes-after-sorting-a-vector-in-c-stl/
I still don't understand how can I apply that on my example.
The thing is that I don't want and can't use use vectors, lambdas or any predefined sort
function that the programming language can have.
Yes, this is for school.
I am sorry, but I am oblivious on how this works.