From c11e57d8ae3334b6e7793c2e1770e8edca1507fe Mon Sep 17 00:00:00 2001 From: FiTeen Date: Fri, 20 Dec 2019 20:08:14 +0800 Subject: [PATCH] feat: delete duplicate code --- BubbleSort/README.md | 12 ++++-------- BubbleSort/bubble_sort.c | 18 ++++++++++-------- QuickSort/README.md | 7 ------- QuickSort/quick_sort.c | 1 - 4 files changed, 14 insertions(+), 24 deletions(-) diff --git a/BubbleSort/README.md b/BubbleSort/README.md index 3796260..c0884f4 100644 --- a/BubbleSort/README.md +++ b/BubbleSort/README.md @@ -18,13 +18,11 @@ #### C语言 ```c void bubble_sort(int arr[], int n) { - int i, j, tmp; + int i, j; for (i = 0; i < n - 1; i++) { for (j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { - tmp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = tmp; + swap(arr, j, j+1); } } } @@ -40,14 +38,12 @@ void bubble_sort(int arr[], int n) { ```c void bubble_sort_quicker(int arr[], int n) { - int i, j, tmp, flag; + int i, j, flag; for (i = 0; i < n - 1; i++) { flag = 0; for (j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { - tmp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = tmp; + swap(arr, j, j+1); flag = 1; } } diff --git a/BubbleSort/bubble_sort.c b/BubbleSort/bubble_sort.c index 3171e56..a6926d1 100644 --- a/BubbleSort/bubble_sort.c +++ b/BubbleSort/bubble_sort.c @@ -1,27 +1,29 @@ #include +void swap(int arr[], int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +} + void bubble_sort(int arr[], int n) { - int i, j, tmp; + int i, j; for (i = 0; i < n - 1; i++) { for (j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { - tmp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = tmp; + swap(arr, j, j+1); } } } } void bubble_sort_quicker(int arr[], int n) { - int i, j, tmp, flag; + int i, j, flag; for (i = 0; i < n - 1; i++) { flag = 0; for (j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { - tmp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = tmp; + swap(arr, j, j+1); flag = 1; } } diff --git a/QuickSort/README.md b/QuickSort/README.md index 05c56b1..24d7c26 100644 --- a/QuickSort/README.md +++ b/QuickSort/README.md @@ -32,13 +32,6 @@ 这里取序列的第一个元素为基准。 ```c -/* 交换位置函数,交换 i 和 j 的位置 */ -void swap(int arr[], int i, int j) { - int temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; -} - /* 选取序列的第一个元素作为基准 */ int select_pivot(int arr[], int low) { return arr[low]; diff --git a/QuickSort/quick_sort.c b/QuickSort/quick_sort.c index 309aa60..99372b0 100644 --- a/QuickSort/quick_sort.c +++ b/QuickSort/quick_sort.c @@ -2,7 +2,6 @@ #include #include -/* 交换位置函数,交换 i 和 j 的位置 */ void swap(int arr[], int i, int j) { int temp = arr[i]; arr[i] = arr[j];