diff --git a/4.shellSort.md b/4.shellSort.md index cfa59f5..e6d5f9c 100644 --- a/4.shellSort.md +++ b/4.shellSort.md @@ -69,7 +69,7 @@ def shellSort(arr): func shellSort(arr []int) []int { length := len(arr) gap := 1 - for gap < gap/3 { + for gap < length/3 { gap = gap*3 + 1 } for gap > 0 { @@ -144,3 +144,23 @@ function shellSort($arr) return $arr; } ``` + +## 7. C++ 代码实现 + +```cpp +void shellSort(vector& arr) { + int gap = 1; + while (gap < (int)arr.size() / 3) { + gap = gap * 3 + 1; + } + for (; gap >= 1; gap /= 3) { + for (int i = 0; i < gap; ++i) { + for (int j = i + gap; j < arr.size(); j += gap) { + for (int k = j; k - gap >= 0 && arr[k] < arr[k - gap]; k -= gap) { + swap(arr[k], arr[k - gap]); + } + } + } + } +} +``` diff --git a/5.mergeSort.md b/5.mergeSort.md index bf0de32..c030d8f 100644 --- a/5.mergeSort.md +++ b/5.mergeSort.md @@ -222,4 +222,41 @@ function merge($left, $right) return $result; } -``` \ No newline at end of file +``` + +## 9. C++ 代码实现 + +```cpp +void merge(vector& arr, int l, int mid, int r) { + int index = 0; + int ptrL = l; + int ptrR = mid; + static vectortempary; + if (arr.size() > tempary.size()) { + tempary.resize(arr.size()); + } + while (ptrL != mid && ptrR != r) { + if (arr[ptrL] < arr[ptrR]) { + tempary[index++] = arr[ptrL++]; + } else { + tempary[index++] = arr[ptrR++]; + } + } + while (ptrL != mid) { + tempary[index++] = arr[ptrL++]; + } + while (ptrR != r) { + tempary[index++] = arr[ptrR++]; + } + copy(tempary.begin(), tempary.begin() + index, arr.begin() + l); +} +void mergeSort(vector& arr, int l, int r) { // sort the range [l, r) in arr + if (r - l <= 1) { + return; + } + int mid = (l + r) / 2; + mergeSort(arr, l, mid); + mergeSort(arr, mid, r); + merge(arr, l, mid, r); +} +``` diff --git a/src/pythonSortTest.py b/src/pythonSortTest.py index ea765d2..bf092db 100644 --- a/src/pythonSortTest.py +++ b/src/pythonSortTest.py @@ -1,4 +1,4 @@ -''' +''' # Create by LokiSharp(loki.sharp#gmail) at 2017-1-22 ''' @@ -176,6 +176,34 @@ def countingSort(arr, maxValue=None): bucket[j] -= 1 return arr +def radix_count(exp1): + global list + n = len(list) + output = [0] * (n) + count = [0] * (10) + for i in range(0, n): + index = (list[i] / exp1) + count[(index) % 10] += 1 + for i in range(1,10): + count[i] += count[i - 1] + i = n - 1 + while i >= 0: + index = (list[i]/exp1) + output[count[(index) % 10] - 1] = list[i] + count[(index) % 10] -= 1 + i -= 1 + i = 0 + for i in range(0,len(list)): + list[i] = output[i] + +def radixSort(): + global list + max1 = max(list) + exp = 1 + while max1 / exp > 0: + radix_count(exp) + exp *= 10 + if __name__ == '__main__': sortTest(bubbleSort, TOTAL) @@ -185,3 +213,4 @@ def countingSort(arr, maxValue=None): sortTest(mergeSort, TOTAL) sortTest(quickSort, TOTAL) sortTest(heapSort, TOTAL) + sortTest(radixSort, TOTAL)