#implement bubble sort even though it sucks import random import math class Person(object): def __init__(self, name, age): self.name = name self.age = age def __str__(self): return "Person " + self.name + " is " + str(self.age) + " years old." def test_bubble_sort(): person_list = [] for i in range(10): random_age = random.randint(0,130) person_list.append(Person("Guy" + str(random_age), random_age)) for person in person_list: print person bubble_sort_people(person_list) for person in person_list: print person last_age = -1 for person in person_list: assert person.age >= last_age last_age = person.age print "all tests passed" def bubble_sort_people(person_list): done_sorting = False while (not done_sorting): done_sorting = True position = 0 while (position < (len(person_list)-1)): if person_list[position].age > person_list[position+1].age: person_list[position], person_list[position+1] = person_list[position+1], person_list[position] done_sorting = False position += 1 def test_merge_sort(): person_list = [] for i in range(10): random_age = random.randint(0,130) person_list.append(Person("Guy" + str(random_age), random_age)) for person in person_list: print person merge_sort_people(person_list) for person in person_list: print person last_age = -1 for person in person_list: assert person.age >= last_age last_age = person.age print "all tests passed" def merge_sort_people(person_list): if len(person_list) < 2: return person_list left = person_list[:int(math.floor(len(person_list)/2))] right = person_list[int(math.ceiling(len(person_list)/2)):] left = merge_sort_people(left) right = merge_sort_people(right) return merge_people(left, right) def merge_people(left, right): merged_list = [] while (len(left) + len(right) > 0) if len(left)==0: return merged_list + right if len(right)==0: return merged_list + left if left[0] <= right[0]: merged_list.append(left[0]) left = left[1:] else: merged_list.append(right[0]) right = right[1:] test_merge_sort()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question