Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

/* The sorting algorithm is to be left as descending There are two logical bugs,

ID: 3725924 • Letter: #

Question

/*
The sorting algorithm is to be left as descending
There are two logical bugs, the number do not sort correctly
Fix it
Comment the code where the bugs where, comment out the original code and
Place your solution BELOW the original code
*/


main()
{
char wait;
short m[]={3,5,7,2,5,1,2,2,  
6,5,7,2,4,1,3,3,
7,7,3,2,5,7,1,9};
unsigned char temp, i, j;
unsigned char numElements = sizeof(m)/sizeof(m[0])-1;

for (i=0; i<=numElements-1; i++) // change < to <=
{
for(j=i+1; j<=numElements; j++) // change < to <=
{
if ( m[i] <= m[j])
{
temp = m[i]; //was m[j] should be m[i]
m[i] = m[j];
m[j] = temp;
}
}
}

Change the actual swapping logic in the scope of the “if” construct, from array references to pointers. This also includes the “temp” identifier. Watch your data typing.

Do not modify the array “m” declaration.

The resulting values in the array “m” will be in descending order. </hint> take the code, compile and link it, run and verify the data in “m” is descending. Then modify one line of code (LOC) to use pointers, comment out the original for reference, compile/link and test. Then change another LOC until all swapping is using pointer identifiers. <hint>

Thanks

Explanation / Answer

Two bugs found are 1) missing braces at the end of the program

and 2)

unsigned char numElements = sizeof(m)/sizeof(m[0]); [eliminate -1] to make it 24 when < is to be used instead of <= (otherwise the value will be 23)

Swapping using pointers can be done using the following code

main()

{

char wait; // declared but not used....may result in warning;
short m[]={3,5,7,2,5,1,2,2,  
6,5,7,2,4,1,3,3,
7,7,3,2,5,7,1,9};
unsigned char temp, i, j;
unsigned char numElements = sizeof(m)/sizeof(m[0]); // -1 removed to get exact number of elements in an array

for (i=1; i<numElements; i++) // change < to <=
{
for(j=0; j<numElements-i; j++) // change < to <=
{
if ( *(m+j)<*(m+j+1))) // swap using pointers
{
temp = *(m+j);

*(m+j)>=*(m+j+1);

     *(m+j+1) = temp;
}
}

}

}