插入排序算法,简单直观的排序算法.工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入.
Python代码如下:
# coding:utf-8 import random class Insert: def main(self): arr_list = [i for i in range(10)] random.shuffle(arr_list) print("Raw list: ", arr_list) self.sort_list(arr_list) def sort_list(self, iterable): for i in range(1, len(iterable)): if iterable[i] < iterable[i - 1]: self.exchange_element(iterable, i) print("Process list: ", iterable) self.sort_list(iterable) @staticmethod def exchange_element(iterable, index): iterable[index], iterable[index - 1] = iterable[index - 1], iterable[index] if __name__ == '__main__': insert = Insert() insert.main() |
结果展示:
Raw list: [6, 4, 7, 0, 9, 5, 8, 2, 1, 3] Process list: [4, 6, 7, 0, 9, 5, 8, 2, 1, 3] Process list: [4, 6, 0, 7, 9, 5, 8, 2, 1, 3] Process list: [4, 0, 6, 7, 9, 5, 8, 2, 1, 3] Process list: [0, 4, 6, 7, 9, 5, 8, 2, 1, 3] Process list: [0, 4, 6, 7, 5, 9, 8, 2, 1, 3] Process list: [0, 4, 6, 5, 7, 9, 8, 2, 1, 3] Process list: [0, 4, 5, 6, 7, 9, 8, 2, 1, 3] Process list: [0, 4, 5, 6, 7, 8, 9, 2, 1, 3] Process list: [0, 4, 5, 6, 7, 8, 2, 9, 1, 3] Process list: [0, 4, 5, 6, 7, 2, 8, 9, 1, 3] Process list: [0, 4, 5, 6, 2, 7, 8, 9, 1, 3] Process list: [0, 4, 5, 2, 6, 7, 8, 9, 1, 3] Process list: [0, 4, 2, 5, 6, 7, 8, 9, 1, 3] Process list: [0, 2, 4, 5, 6, 7, 8, 9, 1, 3] Process list: [0, 2, 4, 5, 6, 7, 8, 1, 9, 3] Process list: [0, 2, 4, 5, 6, 7, 1, 8, 9, 3] Process list: [0, 2, 4, 5, 6, 1, 7, 8, 9, 3] Process list: [0, 2, 4, 5, 1, 6, 7, 8, 9, 3] Process list: [0, 2, 4, 1, 5, 6, 7, 8, 9, 3] Process list: [0, 2, 1, 4, 5, 6, 7, 8, 9, 3] Process list: [0, 1, 2, 4, 5, 6, 7, 8, 9, 3] Process list: [0, 1, 2, 4, 5, 6, 7, 8, 3, 9] Process list: [0, 1, 2, 4, 5, 6, 7, 3, 8, 9] Process list: [0, 1, 2, 4, 5, 6, 3, 7, 8, 9] Process list: [0, 1, 2, 4, 5, 3, 6, 7, 8, 9] Process list: [0, 1, 2, 4, 3, 5, 6, 7, 8, 9] Process list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
算法优化:
# coding:utf-8 import random class Insert: def main(self): arr_list = [i for i in range(10)] random.shuffle(arr_list) print("Raw list: ", arr_list) self.sort_list(arr_list) @staticmethod def sort_list(iterable): for i in range(len(iterable) - 1): for j in range(i + 1, len(iterable)): if iterable[j] < iterable[i]: temp = iterable[j] iterable.remove(iterable[j]) iterable.insert(i, temp) print("Process list: ", iterable) if __name__ == '__main__': insert = Insert() insert.main() |
结果展示:
Raw list: [5, 4, 7, 3, 6, 9, 0, 2, 1, 8] Process list: [4, 5, 7, 3, 6, 9, 0, 2, 1, 8] Process list: [3, 4, 5, 7, 6, 9, 0, 2, 1, 8] Process list: [0, 3, 4, 5, 7, 6, 9, 2, 1, 8] Process list: [0, 2, 3, 4, 5, 7, 6, 9, 1, 8] Process list: [0, 1, 2, 3, 4, 5, 7, 6, 9, 8] Process list: [0, 1, 2, 3, 4, 5, 6, 7, 9, 8] Process list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |