Reputation: 3
I need to output stalls which made profit (if they made profit) in increasing order of profit (lowest profit to highest profit). When I run my program, it outputs it in increasing order but only excludes one instance of profit that is < 0 and outputs the rest. What am I doing wrong?
Below is the code I'm using to exclude stalls that made a profit of < 0
for (int i = 0; i < n; i++){
if (Stalls[i].net < 0){
for (int j = i + 1; j < n; ++j){
Stalls[j - 1] = Stalls[j];}
n--;}
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (Stalls[i].net > Stalls[j].net) {
Stall tmp = Stalls[i];
Stalls[i] = Stalls[j];
Stalls[j] = tmp;
}
}
}
for (int i = 0; i < n; i++)
of << Stalls[i].name << endl;
Upvotes: 0
Views: 58
Reputation: 27
My answer is not complete answer, but I found the main problem on the code.
# Remove negative items
for (int i = 0; i < n; i++)
{
if (Stalls[i].net < 0)
{
printf(" i = %d, %d\n", i, Stalls[i].net);
for (int j = i + 1; j < n; ++j)
{
// strcpy(Stalls[j - 1].name, Stalls[j].name);
// Stalls[j - 1].net = Stalls[j].net;
Stalls[j - 1] = Stalls[j];
}
n--;
}
}
This function have problem
If data
is [-3, -2, -1, 0, 1, 2]
After above for
loop, data
is [-2, 0, 1, 2, 2, 2]
But, we can think, the data
is [0, 1, 2, 2, 2, 2]
Why:
-3 -2 -1 0 1 2
The index of -3
is 0,
With Stalls[j - 1] = Stalls[j];
, -3
is replace with -2
,
and -2
move to 0th position,
But, -2
cannot check with if (Stalls[i].net < 0)
, because the i
is already increased
So, the -2
is remain
Easily answer: (Not optimized)
// Remove negative items
for (int k = 0; k < n; k++) // This is added loop
for (int i = 0; i < n; i++)
{
if (Stalls[i].net < 0)
{
printf(" i = %d, %d\n", i, Stalls[i].net);
for (int j = i + 1; j < n; ++j)
{
// strcpy(Stalls[j - 1].name, Stalls[j].name);
// Stalls[j - 1].net = Stalls[j].net;
Stalls[j - 1] = Stalls[j];
}
n--;
}
}
Upvotes: 1