Python选择排序算法(面向对象写法)

tech2022-10-28  116

"""选择排序""" class SelectionSort(object): def __init__(self, li): self.li = li self.min_index = None # 初始时设置列表的最小值为空值 def campare_elem(self, m, n): """比较元素""" if self.li[m] > self.li[n]: self.min_index = n def exchange_elem(self, m, n): """交换元素位置""" self.li[m], self.li[n] = self.li[n], self.li[m] def selection_sort(self): for i in range(len(self.li)-1): self.min_index = i for j in range(i+1, len(self.li)): self.campare_elem(self.min_index, j) self.exchange_elem(self.min_index, i) return self.li if __name__ == "__main__": li = [9, 0, 1, 6, 5, 2, 12, 10, 8, 21, 7] selection = SelectionSort(li) print(selection.selection_sort())
最新回复(0)