1c - Sorting1

# Programming applied 2134 5 6 7 8 9 bubble sort applied

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: does the value Item go? Where Item Pos = 0; while (Pos &lt; i &amp;&amp; Item &gt;= X[Pos]) Pos++; Pos now has the value of the index at which Item now must go, either at Pos=i or before X[Pos]. Pos=i or X[Pos] Applied Programming Applied If it goes at the end, then X[Pos] = Item; i++; But, in the other case, there's no space before But, X[Pos] for the value, so we have to move all the X[Pos] for other values up. other for (j=i-1;j&gt;=Pos;j--) X[j+1] = X[j]; The code at the top of the screen will place Item The Item in the right spot. Applied Programming W e can combine both these steps, by searching We for the insertion spot from the end of the current contents, moving the elements up as we go. contents, Pos = i-1; while (Pos &gt;= 0 &amp;&amp; Item &lt; X[Pos]) { X[Pos+1] = X[Pos]; Pos--; } X[Pos+1] = Item; i++; Applied Programming Applied Programming W e can extend the algorithm to sorting an array We which is already occupied. which Assume that X[0] is the only part already sorted. Assume X[0] 9 Use the code above to insert Item = X[1]; into the sub-array. Then insert Item = X[2]; and so on. 6 4 3 8 7 2 5 1 Insertion Sort Applied Programming Applied Programming 4 9 6 3 8 7 2 5 1 4 9 6 Insertion Sort 3 8 7 2 5 Insertion Sort Applied Programming Applied 9 6 4 3 8 7 2 5 1 Applied Programming 6 9 Insertion Sort 4 3 8 7 2 5 9 3 8 7 1 Insertion Sort Applied Programming 6 1 2 5 1 4 Applied Programming 6 9 3 8 7 2 5 1 4 Insertion Sort Insertion Sort Applied Programming Applied Programming 6 9 3 8 7 2 5 1 4 6 9 3 8 7 2 5 4 Insertion Sort Insertion Sort Applied Programming Applied 6 1 9 3 8 7 2 5 1 Applied Programming 4 6 9 3 8 7 2 5 1 4 Insertion Sort Insertion Sort Applied Programming 4 6 9 8 7 2 5 1 3 Applied Programming 4 6 9 8 7 2 5 1 3 Insertion Sort Insertion Sort Applied Programming Applied Programming 4 6 9 8 7 2 5 1 3 4 6 9 8 7 2 5 3 Insertion Sort Insertion Sort Applied Programming Applied 34 6 9 8 7 2 5 1 Applied Programming 34 6 9 7 2 5 Applied Programming 6 9 7 1 8 Insertion Sort 34 1 2 5 1 8 Applied Programming 34 6 8 9 7 2 5 1 Insertion Sort Applied Programming Applied Programming 34 6 8 9 2 5 1 34 7 Insertion Sort 6 8 9 2 5 7 Insertion Sort Applied Programming Applied 34 6 8 9 2 5 1 Applied Programming 34 7 Insertion Sort 6 7 8 9 2 5 6 7 8 9 1 Insertion Sort Applied Programming 34 1 5 1 2 Applied Programming 34 6 7 8 9 5 1 2 Insertion Sort Insertion Sort Applied Programming Applied Programming 34 6 7 8 9 5 1 34 2 6 7 8 9 5 2 Inserti...
View Full Document

Ask a homework question - tutors are online