|
4 | 4 |
|
5 | 5 | static void show(int *nums, int lo, int hi) |
6 | 6 | { |
7 | | - int i; |
8 | | - for (i = lo; i <= hi; i++) { |
9 | | - printf("%d ", nums[i]); |
10 | | - } |
11 | | - printf("\n"); |
| 7 | + int i; |
| 8 | + for (i = lo; i <= hi; i++) { |
| 9 | + printf("%d ", nums[i]); |
| 10 | + } |
| 11 | + printf("\n"); |
12 | 12 | } |
13 | 13 |
|
14 | 14 | static inline void swap(int *a, int *b) |
@@ -52,16 +52,70 @@ static void quick_sort(int *nums, int lo, int hi) |
52 | 52 | quick_sort(nums, i + 1, hi); |
53 | 53 | } |
54 | 54 |
|
| 55 | +static void merge(int *nums, int lo, int mid, int hi) |
| 56 | +{ |
| 57 | + int i, j, k, size = hi - mid; |
| 58 | + int *tmp = malloc(size * sizeof(int)); |
| 59 | + |
| 60 | + for (j = 0; j < size; j++) { |
| 61 | + tmp[j] = nums[mid + 1 + j]; |
| 62 | + } |
| 63 | + |
| 64 | + i = mid; |
| 65 | + j = size - 1; |
| 66 | + k = hi; |
| 67 | + while (i >= lo && j >= 0) { |
| 68 | + if (tmp[j] >= nums[i]) { |
| 69 | + nums[k--] = tmp[j--]; |
| 70 | + } else { |
| 71 | + nums[k--] = nums[i--]; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + while (j >= 0) { |
| 76 | + nums[k--] = tmp[j--]; |
| 77 | + } |
| 78 | + |
| 79 | + free(tmp); |
| 80 | +} |
| 81 | + |
| 82 | +static void merge_sort(int *nums, int lo, int hi) |
| 83 | +{ |
| 84 | + int mid; |
| 85 | + |
| 86 | + if (lo >= hi) { |
| 87 | + return; |
| 88 | + } |
| 89 | + |
| 90 | + mid = lo + (hi - lo) / 2; |
| 91 | + |
| 92 | + merge_sort(nums, lo, mid); |
| 93 | + merge_sort(nums, mid + 1, hi); |
| 94 | + |
| 95 | + merge(nums, lo, mid, hi); |
| 96 | +} |
| 97 | + |
| 98 | +int *sortArray(int *nums, int numsSize, int *returnSize) |
| 99 | +{ |
| 100 | +#if 1 |
| 101 | + quick_sort(nums, 0, numsSize - 1); |
| 102 | +#else |
| 103 | + merge_sort(nums, 0, numsSize - 1); |
| 104 | +#endif |
| 105 | + *returnSize = numsSize; |
| 106 | + return nums; |
| 107 | +} |
| 108 | + |
55 | 109 | int main(int argc, char **argv) |
56 | 110 | { |
57 | 111 | int i, count = argc - 1; |
| 112 | + int ret_size = 0; |
58 | 113 | int *nums = malloc(count * sizeof(int)); |
59 | 114 | for (i = 0; i < count; i++) { |
60 | 115 | nums[i] = atoi(argv[i + 1]); |
61 | 116 | } |
62 | 117 |
|
63 | | - quick_sort(nums, 0, count - 1); |
64 | | - show(nums, 0, count - 1); |
| 118 | + show(sortArray(nums, count, &ret_size), 0, ret_size - 1); |
65 | 119 |
|
66 | 120 | return 0; |
67 | 121 | } |
0 commit comments