你想要做的就是使用冒泡:
def bubble_sort(list_of_students):
"""
Runs the bubble sort algorithm on the student class
@rtype : list
@param list_of_students: List of students to be sorted
@type list_of_students: list
"""
for _ in list_of_students:
for j in xrange(len(list_of_students) - 1):
if list_of_students[j] > list_of_students[j + 1]:
list_of_students[j + 1], list_of_students[j] = list_of_students[j], list_of_students[j + 1]
return list_of_students
嘗試以下操作:
from random import randint, choice
import string
class Student(object):
def __init__(self, name, grade):
self.name = name
self.grade = grade
def __gt__(self, other):
if isinstance(other, Student):
return self.name > other.name
raise Exception("Cannot compare Student to Not-A-Student")
def __repr__(self):
return "{name} => {grade}".format(name=self.name, grade=self.grade)
def bubble_sort(list_of_students):
"""
Runs the bubble sort algorithm on the student class
@rtype : list
@param list_of_students: List of numbers to be sorted
@type list_of_students: list
"""
for _ in list_of_students:
for j in xrange(len(list_of_students) - 1):
if list_of_students[j] > list_of_students[j + 1]:
list_of_students[j + 1], list_of_students[j] = list_of_students[j], list_of_students[j + 1]
return list_of_students
l = [Student(choice(string.ascii_uppercase), randint(0, 10)) for i in range(10)]
print bubble_sort(l)
你有沒有在所有研究任何排序算法? –
這段代碼會導致異常 - 對於最後一個值(討厭單字母ID)它會拋出異常 – volcano
我知道冒泡排序,選擇排序,快速排序和合並排序,但不正確的行是studentList [i] .getName ()= studentList [i + 1] .getName() studentList [i + 1] .getName()= aux – user1012732