From d4ff312bbd40ceb003a653f84233ede05497d5c1 Mon Sep 17 00:00:00 2001 From: SunnyQjm Date: Tue, 23 Jun 2020 15:27:59 +0800 Subject: [PATCH] add: sort --- chapter5/5_bubble-sort.py | 34 ++++++++++++++++++++++++++++++++++ chapter5/6_select-sort.py | 22 ++++++++++++++++++++++ chapter5/7_insert-sort.py | 23 +++++++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 chapter5/5_bubble-sort.py create mode 100644 chapter5/6_select-sort.py create mode 100644 chapter5/7_insert-sort.py diff --git a/chapter5/5_bubble-sort.py b/chapter5/5_bubble-sort.py new file mode 100644 index 0000000..120a667 --- /dev/null +++ b/chapter5/5_bubble-sort.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# coding=utf-8 + +################################################################################### +# 冒泡排序 +################################################################################### + + +# 第一轮采用正向遍历的冒泡排序代码示例 +def bubbleSort(A): + n = len(A) + for i in range(n - 1): + for j in range(n - i - 1): + if A[j] > A[j + 1]: + A[j], A[j + 1] = A[j + 1], A[j] + + +# 第一轮采用反向遍历的冒泡排序代码示例 +def bubbleSort2(A): + n = len(A) + for i in range(n - 1, 0, -1): + for j in range(i): + if A[j] > A[j + 1]: + A[j], A[j + 1] = A[j + 1], A[j] + + +if __name__ == '__main__': + A = [5, 7, 1, 3, 6, 2, 4] + bubbleSort(A) + print(A, "= [1, 2, 3, 4, 5, 6, 7]") + + A = [5, 7, 1, 3, 6, 2, 4] + bubbleSort2(A) + print(A, "= [1, 2, 3, 4, 5, 6, 7]") diff --git a/chapter5/6_select-sort.py b/chapter5/6_select-sort.py new file mode 100644 index 0000000..9332da5 --- /dev/null +++ b/chapter5/6_select-sort.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +# coding=utf-8 + +################################################################################### +# 选择排序 +################################################################################### + + +def selectSort(A): + n = len(A) + for i in range(n - 1): + minValueIndex = i + for j in range(i + 1, n): + if A[j] < A[minValueIndex]: + minValueIndex = j + A[i], A[minValueIndex] = A[minValueIndex], A[i] + + +if __name__ == '__main__': + A = [5, 7, 1, 3, 6, 2, 4] + selectSort(A) + print(A, "= [1, 2, 3, 4, 5, 6, 7]") diff --git a/chapter5/7_insert-sort.py b/chapter5/7_insert-sort.py new file mode 100644 index 0000000..e37b585 --- /dev/null +++ b/chapter5/7_insert-sort.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python +# coding=utf-8 + +################################################################################### +# 插入排序 +################################################################################### + + +def insertSort(A): + n = len(A) + for i in range(1, n): + curIndex = i + for j in range(curIndex - 1, -1, -1): + if A[j] > A[curIndex]: + A[j], A[curIndex], curIndex = A[curIndex], A[j], j + else: + break + + +if __name__ == '__main__': + A = [5, 7, 1, 3, 6, 2, 4] + insertSort(A) + print(A, "= [1, 2, 3, 4, 5, 6, 7]")