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.

  1. Add comments, fix logic and retain original code in comments to make the algorithm functionally correct.
  2. 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.
    1. 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

  1. Given an array of length n,
    1. For element 0
      1. Search elements 0 through n-1
        1. Swapping element 0 with a smaller element
    2. For element 1
      1. Search elements 1 through n-1
        1. Swapping element 1 with a smaller element
    3. For element 2
      1. Search elements 2 through n-1
        1. Swapping element 2 with a smaller element
    4. For element 3
      1. Search elements 3 through n-1
        1. Swapping element 3 with a smaller element
    5. Continue in this fashion until theres nothing left to search

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!