CSE 1540.03
Week 6.2.1
February 8, 2012
Arrays
Problem:
print three variables
a,
b,
c
in decreasing order
if (a .GT. b) then
if (c .GT. a) then
print*, c, a, b
c > a, a > b
else
if (b .GT. c) then
print*, a, b, c
a > b, c
a, b > c
≤
else
print*, a, c, b
a > b, c
a, b
c
≤
≤
end if
end if
else
if (c .GT. b) then
print*, c, b, a
a
b, c > b
≤
else
if (a .GT. c) then
print*, b, a, c
a
b, c
b, a > c
≤
≤
else
print*, b, c, a
a
b, c
b, a
c
≤
≤
≤
end if
end if
end if
Better approach:
if (a .LT. b) then
temp = a
a = b
b = temp
end if
know
a
b
≥
if (b .LT. c) then
temp = b
b = c
c = temp
end if
know
b
c
≥
⇒
smallest in
c
if (a .LT. b) then
temp = a
a = b
b = temp
end if
second smallest in
b,
largest in
a
print*, a, b, c
Pattern:
if (x .LT. y) then
Bubble Sort
temp = x
x = y
y = temp
end if
Bubble Sort
integer n, i, j
real ar(6), temp
n = 6
do j = n-1, 1, -1
do i = 1, j
if (ar(i) .gt. ar(i+1)) then
temp = ar(i)
ar(i) = ar(i+1)
ar(i+1) = temp
end if
CSE 1540
Week 6.2.1 – February 8, 2012
page 1 of 2