Question: A simple sorting algorithm (Selection Sort - kind of) see Appendix B for an unsorted single dimensional array is to use two loops. The outer
A simple sorting algorithm (Selection Sort - kind of) see Appendix B for an unsorted single dimensional array is to use two loops. The outer loop (i) for each element except for the last, will compare and swap data for every inner loop (j) for each element starting at the next outer loop index. See Appendix A for a code example. The code example is to sort an array in descending order. This is not a Bubble sort, just another simplified sorting algorithm. So stay away from the internet and use your brain, you may have to do this on a test, without the aid of Bing or Google.
- Add comments, fix logic and retain original code in comments to make the algorithm functionally correct.
- The Analysis; capture the number of outer loops, number of inner loops and number of swaps (You may have to instrument your code). Elicit more information.
- Does the code behave: number of outer-loops = n-1, inner-loops = n/2 and conditionals about 40% swaps? Where n is the number of elements.
Your assignment is to understand how the sort should work, debug the code in Appendix A, and supply the fixes.
Appendix A
The following code will sort an array in descending order. Keep it as Descending. However, it has two logic bugs.
/*
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 { for(j=i+1; j { if ( m[i] <= m[j]) { temp = m[j]; m[i] = m[j]; m[j] = temp; } } } } Appendix B Analysis of a Buggered Sort ascending order
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
