sort1.py
#!/usr/bin/env python
#
# Author: Yotam Medini [email protected] -- Created: 2005/September/12
#
# Create random list of integers, show, sort, and show again
#
import random
import sys
size = 8
nums = size * [0] # start with a list with zeros.
# Get random numbers within -1000 .. +1000
i = 0
while i < size:
nums[i] = random.randrange(-1000, 1001) # Randomly get a number
i = i + 1
# Show the random list
sys.stdout.write("Random list:")
i = 0
while i < size:
sys.stdout.write(" %d" % nums[i])
i = i + 1
sys.stdout.write("\n")
# Sort
i = 0
while i < size:
# Find the minimum in the 'tail' nums[i:]
mi = i # May be this is where
m = nums[mi] # the minimum is.
j = i + 1
while j < size:
if m > nums[j]:
# We found a smaller number in the tail
mi = j
m = nums[mi]
j = j + 1
# We found the minimum of the tail.
# We need to put it in the right place,
# which is the beginning of the tail.
# so we exchange places.
t = nums[i]
nums[i] = nums[mi] # This is actually: m
nums[mi] = t
i = i + 1 # Short the tail.
# Show the sorted list
sys.stdout.write("Sorted list:")
i = 0
while i < size:
sys.stdout.write(" %d" % nums[i])
i = i + 1
sys.stdout.write("\n")
sys.exit(0)
Generated by GNU enscript 1.6.4.