Created
February 23, 2010 18:22
-
-
Save stevenwilkin/312520 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# sort this list of random numbers using bubble sort algorithm | |
nums = [35, 59, 30, 95, 97, 45, 44, 41, 80, 78, 14, 58, 2, 41, 6, 68, 18, 13, 69, 12] | |
# test if the list is sorted | |
def sorted(arr): | |
prev = arr[0] | |
for x in arr: | |
if x < prev: | |
return False | |
prev = x | |
return True | |
# print the list | |
def print_nums(arr): | |
for x in arr: | |
print x | |
# perform a single pass of bubble sort | |
def bubble_pass(arr): | |
for i in range(0, len(arr) - 1): | |
if arr[i + 1] < arr[i]: | |
tmp = arr[i] | |
arr[i] = arr[i + 1] | |
arr[i + 1] = tmp | |
return arr | |
# keep performing bubble sort until the list is sorted | |
def bubble_sort(arr): | |
while not sorted(arr): | |
arr = bubble_pass(arr) | |
return arr | |
print_nums(bubble_sort(nums)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment