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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include<iostream> #include<string>
using namespace std;
int n = 10; int* B = (int*)malloc(n * sizeof(int)); int* B2 = new int[n];
void Merge(int A[],int low,int mid,int high) { int i, j, k; for ( k = low; k <= high; k++) { B[k] = A[k]; } for (i = low,j = mid+1,k = i;i<=mid&&j<=high; k++) { if (B[i] <= B[j]) { A[k] = B[i++]; } else { A[k] = B[j++]; } } while (i<=mid) { A[k++] = B[i++]; } while (j <= high) { A[k++] = B[j++]; } }
void MergeSort(int A[],int low,int high) { if (low<high) { int mid = (low + high) / 2; MergeSort(A, low, mid); MergeSort(A, mid+1, high); Merge(A, low, mid, high); } }
int main() { int a[] = { 3,5,2,6,1,4,9,8 }; MergeSort(a, 0, 7); cout << "归并排序后:" << endl; for (int i = 0; i < 8; i++) { cout << a[i]; if (i == 7) { cout <<endl;; } else { cout << ","; } } return 1; }
|