Beruflich Dokumente
Kultur Dokumente
for k = 1 to n 1 do
if xk > xk+1 then
y := xk
xk := xk+1
xk+1 := y
end
end
But once it has executed, the list still may not be in numeric order. For example,
if the smallest entry happens to be at the very end of the list, it has only been
moved one position down. In fact, any list entry is moved at most one position
down or one position up. To fully sort the list we must run this for loop n 1
times. Here is our final algorithm.
Solutions for Chapter 5 145
Algorithm
Input: A list of numbers x1 , x2 , x3 . . . , xn
Output: The list in numeric order
begin
for i := 1 to n 1 do
for k = 1 to n 1 do
if xk > xk+1 then
y := x k
xk := xk+1
xk+1 := y
end
end
end
end
output match
Algorithm
Input: A list of numbers x1 , x2 , x3 . . . , xn
Output: "YES" if the list has repetition, otherwise "NO"
begin
match := NO
for i := 1 to n 1 do
for k = i + 1 to n do
if x i = xk then
match := YES
end
end
end
end
output match
7. Write an algorithm whose input is two positive integers n, k, and whose output
is the number of non-negative integer solutions of the equation x1 + x2 + x + x3 +
+ xk = n. (See Section 3.9.)
Solution: As in Section 3.9 we can model the solutions with stars-and-bars lists
x1 x2 x3 xk
z }| { z }| { z }| { z }| {
,
146 Algorithms
having n stars and k 1 bars. Such a list has length n + k 1, and can be
made by choosing n positions for stars and filling the remaining k 1 with bars.
Thus there are n+nk1 such lists, so this is also the number of solutions to the
equation. Thus our algorithm must simply compute n+nk1 . For this we can
n+k1
Algorithm 16: to compute n
Input: Positive
n+k1
integers n and k
Output: n
begin
y := 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . y is initially 1
for i := k to n + k 1 do
y := y i . . . . . . . . . . . . . . . . . . . multiply y by i , for each k i n + k 1
end
for i := 1 to k do
y
y := . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . divide y by i , for each 1 i k
k
end
output y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . now y = n+nk1
end
for x := 0 to n do
for y := 0 to x do
for z := 0 to y do
Command
end
end
end
Command is executed.
11. It computes the average of the input numbers.