Reputation: 13
I have an array of letterData structs titled letters like this:
struct letterData
{
char letter = '0';
double occurrencePercent = 0;
int letterOccurrences = 0;
};
int main()
{
letterData letters[26];
}
I'm attempting to sort this array of structs by the occurrencePercent member like this:
do
{
bool swapped = false;
for (int count = 0; count < 25; count++)
{
if (letters[count].occurrencePercent < letters[count + 1].occurrencePercent)
{
swap(letters[count], letters[count + 1]);
swapped = true;
}
}
} while (swapped);
int width = 0;
for (int count = 0; count < 25; count++)
{
if (letters[count].occurrencePercent == 0)
width = 36;
else
width = 30;
cout << "\n" << letters[count].letter << ": " << letters[count].occurrencePercent << '%';
cout << right << setw(width) << standLetters[count].letter << ": " << standLetters[count].occurrencePercent << '%';
}
Also, here is my swap function:
void swap(struct letterData& a, struct letterData& b)
{
struct letterData temp;
temp = a;
a = b;
b = temp;
}
However, the array isn't sorting properly. Here's what the debugger looks like:
Given Letter Frequency Standard Letter Frequency
b: 8.05085% e: 12.02%
a: 1.69492% t: 9.1%
d: 2.54237% a: 8.12%
c: 0% o: 7.68%
f: 2.54237% i: 7.31%
g: 8.47458% n: 6.95%
h: 11.0169% s: 6.28%
i: 1.69492% r: 6.02%
e: 0% h: 5.92%
k: 4.23729% d: 4.32%
l: 2.54237% l: 3.98%
m: 2.54237% u: 2.88%
n: 1.27119% c: 2.71%
o: 5.50847% m: 2.61%
p: 9.32203% f: 2.3%
q: 8.47458% y: 2.11%
r: 5.50847% w: 2.09%
s: 1.69492% g: 2.03%
t: 6.77966% p: 1.82%
u: 1.27119% b: 1.49%
v: 1.27119% v: 1.11%
w: 8.05085% k: 0.69%
x: 5.50847% x: 0.17%
j: 0% q: 0.11%
y: 0% j: 0.1%
On the left column, the highest percentages should be on top and vice versa. Why isn't it working?
Upvotes: 1
Views: 45
Reputation: 142
For your original function, the only change I had to make to get it to compile and sort correctly was to move the declaration of swapped outside the do...while loop.
My suspicion is that you had that variable declared somewhere else in your code, which avoided the compile error, but then the second declaration shadowed your variable and the do...while did not correctly detect that the swap had occurred and only performed one pass on the loop.
bool swapped = false;
do
{
swapped = false;
for (int count = 0; count < 25; count++)
{
if (letters[count].occurrencePercent < letters[count + 1].occurrencePercent)
{
swap(letters[count], letters[count + 1]);
swapped = true;
}
}
} while (swapped);
Upvotes: 1