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

Since some sorting algorithms are more efficient when the input list is close to

ID: 3662175 • Letter: S

Question

Since some sorting algorithms are more efficient when the input list is close to sorted, we might be able to quickly sort a list by first checking how close the input list is to already being sorted, and then using that information to help us choose which sorting algorithm to use. One measurement of how close a list is to being sorted is the "move distance." Given an input list L of length n such that each number 1, 2, ..., n appears exactly once, define the "move distance" of L as the sum of the number of positions that each list element must be moved to get its correct sorted position. Example: The move distance of 3, 4, 1, 5, 2, is 2+2+2+1+3 = 10 because 3 is 2 positions away from position 3, 4 is 2 positions away from position 4 and so on. The move distance of a list L gives us a sense of how far away list l is from being sorted. Write pseudo code that returns the move distance of any input list consisting of each number 1,2, ..., n appearing exactly once. Analyze the runtime of your algorithm using Theta notation.

Explanation / Answer

"Adequate"

FOR X = 1 to 10
    FOR Y = 1 to 10
        IF gameBoard[X][Y] = 0
            Do nothing
        ELSE
            CALL theCall(X, Y) (recursive method)
            increment counter                 
        END IF
    END FOR
END FOR

"Better"

Set moveCount to 1
FOR each row on the board
    FOR each column on the board
        IF gameBoard position (row, column) is occupied THEN
            CALL findAdjacentTiles with row, column
            INCREMENT moveCount
        END IF
    END FOR
END FOR

FOR all the number at the back of the array
    SET Temp equal the addition of each number
    IF > 9 THEN
        get the remainder of the number divided by 10 to that index
        and carry the "1"
    Decrement one
Do it again for numbers before the decimal

"Good Enough (not perfect)"

SET Carry to 0
FOR each DigitPosition in Number from least significant to most significant

    COMPUTE Total as sum of FirstNum[DigitPosition] and SecondNum[DigitPosition] and Carry  

    IF Total > 10 THEN
        SET Carry to 1
        SUBTRACT 10 from Total
    ELSE
        SET Carry to 0
    END IF

    STORE Total in Result[DigitPosition]

END LOOP  

IF Carry = 1 THEN
    RAISE Overflow exception
END IF