1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #include<iostream> #include<vector>
using namespace std;
int temp[7] = {0}; void merge(int nums[], int low, int mid, int high) { for(int i=low; i<=high;i++){ temp[i] = nums[i]; } int i=0, j=0, k=0; for(i=low, j=mid+1, k=i;i<=mid&&j<=high;k++){ if(temp[i]<=temp[j]){ nums[k] = temp[i++]; } else { nums[k] = temp[j++]; } } while(i<=mid) nums[k++] = temp[i++]; while(j<=high) nums[k++] = temp[j++]; } void merge_sort(int nums[], int low, int high){ if(low < high) { int mid = (low + high) / 2; merge_sort(nums, low, mid); merge_sort(nums, mid + 1, high); merge(nums, low, mid, high); } }
int main() { int nums[] = {3, 5, 1, 4, 8, 6, 2}; merge_sort(nums, 0, 6); for(int i=0;i<7;i++){ printf("%d ", nums[i]); } printf("\n"); system("pause"); return 0; }
|