I was given an assignment to work through in university and one part of that assignment was to add stars(*
) to elements moved in an array using bubble sort. I've tried a few different things to try to get this to work but nothing ends up working. Here is what's specifically asked of me:
"5. Create an extra array of bools (one for each element in the array), so that if a pair of elements are changed round in a cycle, the bools change to true, and those elements are displayed surrounded by stars (
*
) to show that the change has occurred. Then reset the array of bools to false, ready for the next cycle. REMEMBER you need to TEST the value of the Boolean in order to decide whether to output the asterisks or not"
Here is my code:
int main()
{
double Numbers[NMAX] = {31.2, 29.7, 53.5, 69.0, 23.7, 71.8, 49.3, 52.9, 51.3, 57.1};
bool change[NMAX] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
// note this top counter, i, counts down
int counter = 0;
for (int i=NMAX-1; i>0; i--)
{
//and this counter, j, only goes as far as the current i value
// it means it doesn't go over the elements that have already 'bubbled up' to the end of the array
for (int j=0; j<i; j++)
{
double temp;
// Compare 2 values - increment a counter here
counter++;
if (Numbers[j]>Numbers[j+1])
{
temp = Numbers[j];
Numbers[j]= Numbers[j+1];
Numbers[j+1]= temp;
cout << "Array: " << endl;
change[j] = true;
change[j + 1] = true;
for (int i = 0; i < 10; i++)
{
cout << Numbers[i] << ", ";
}
}
}
}
// display the sorted array:
cout << endl;
cout<<"ARRAY CONTENTS SORTED, IMPLEMENTATION 1 "<<endl;
for (int i=0; i<NMAX; i++)
{
cout<<Numbers[i]<<endl;
}
//Display the values of the counter after the whole sort
return 0;
}
I'm fairly new to stackoverflow, so apologies if my question is irritatingly formatted.
I don't understand why that extra array of bool
s was required if
you still remember the j
and j+1
were exchanged when you output Numbers
. I would write simply:
for (int n = 0; n < NMAX; ++n)
{
if (n == j + 1 || n == j)
cout << '*' << Numbers[n] << "*, ";
else
cout << Numbers[n] << ", ";
}
However if there was such a requirement then follow it and try to achieve same effect by checking contents of that bool
array of yours. Also remember to reset it back to false
like required.