You are on page 1of 2

Problem. Given an array of numbers A = (al, az,. . . .

an), sort these numbers into increasing order, that is, arrange the numbers within the array so that a 1 < a25a3s <an. Algorithm SELECTSORT STEP 1. Input A, an array of n numbers STEP 2. For i = 1 to n 1 do {Find the correct ith number.] Begin STEP 3. Set TN:= ai {TN = temporary number} ST E P4. Forj=i+l tondo STEP 5. If aj < TN, switch aj and TN STEP 6. Set ai := TN End {Step 2} STEP 7. Output A and stop. 6:2 SEARCHING A SORTED FILE Problem. Given an array A = (al, a2,. . . . a.) whose elements are numbers liste d in increasing order and a number S, determine S s position in A, that is, find an index i (if it exists) such that ai = S. Algorithm BINARYSEARCH STEP 1.Input A, an array of n numbers in increasing order, and a number S STEP 2.Set first:= 1, last:= n STEP 3.While first <= last do Begin STEP 4. Set mid:= L(first + last)/2] STEP 5. If S = amid, then output found S at location mid and stop. STEP 6. If S < amid, then set last : = mid 1, Else set first : = mid + 1 End {Step 3} STEP 7. Output S is not in A and stop.

Example 2.1. Table 6.2 is a trace of BINARYSEARCH, where A= (3,4,6,7,9,11) and S = 9. We begin after the first encounter with step 4. Table 6.2 Step No. jhst last mid amid 4 5 6 4 5 1 1 4 4 4 6 6 6 6 6 3 3 3 5 5 6 6 6 9 9

'-------------------------------------------We develop the procedure BININSERT that will insert a number D into its correct position in an ordered array. BINARYSORT, which will be our first efficient sorting routine. Procedure BININSERT(r, al,. . . . a,, a, + ~) {The initial segment of the procedure finds the correct location for a,+,.] STEP 1. Set first : = 1, last := r STEP 2. While first <= last do

Begin STEP 3. Set mid:= L(first + last)/2] STEP 4. If ar + I < amid , then set last:= mid I, Else set first : = mid + 1 End {Step 2} {At this point first equals last +1, and first gives the correct position for ar +l. The next segment creates a space for and inserts ar+1.} STEP 5. If first = r + 1, then Return. {ar+1 s place is correct.} STEP 6. Set temp: = ar+1 {save ar+1} STEP 7. For j = r + 1 down to (first + 1) do STEP 8. aj := aj-l STEP 9. Set afirst: = temp STEP 10. Return. Example 3.1. Table 6.3 is a trace of the procedure BININSERT given the array A = (3,5,8, 10, 14), r = 5, and D = 11. Table 6.3 Step No. jirst 3 1 4 4 3 4 4 5 3 5 4 5 8 5 9 5 last 5 5 5 5 5 4 mid 3 3 4 4 4 amid j A 8 (3,5,8, 10,14, 11) 8 10 10 14 6 (3,5,8, 10,14, 14) 6 (3,5,8, 10,11, 14)

You might also like