1 #include <iostream> 2 using namespace std; 3 4 void Merge(int a[], int p, int q, int r) 5 { 6 int n1 = q - p + 1; 7 int n2 = r - q + 1; 8 int *L = new int [n1+1]; 9 int *R = new int [n2+1]; 10 int i, j, k; 11 for (i = 0; i < n1; i ++) 12 L[i] = a[p+i]; 13 for (j = 0; j < n2; j ++) 14 R[j] = a[q+j]; 15 16 L[n1] = 0xFFFF, R[n2] = 0xFFFF; 17 18 i = 0; j = 0; 19 for (k = p; k <= r; k ++){ 20 if (L[i] <= R[j]) 21 a[k] = L[i++]; 22 else 23 a[k] = R[j++]; 24 } 25 } 26 27 void Merge_sort(int a[], int p, int r) 28 { 29 if (p < r){ 30 int q = (p + r)/2; 31 Merge_sort(a, p, q); 32 Merge_sort(a, q+1, r); 33 Merge(a, p, q, r); 34 } 35 } 36 37 int main() 38 { 39 int a[] = {4, 2, 1, 8, 5, 3, 9, 2, 0}; 40 int n = sizeof(a)/ sizeof(a[0]); 41 Merge_sort(a, 0, n-1); 42 for (int i = 0; i < n; i++) 43 cout << a[i] << " "; 44 cout << endl; 45 return 0; 46 }
我能看出来有些地方有错误,但是不知道怎么改啊?有没有哪位大哥能教教我怎么改正确啊?
#include <iostream>
using namespace std;
void Merge(int a[], int p, int q, int r)
{
int n1 = q - p + 1;
int n2 = r - q;
int *L = new int[n1 + 1];
int *R = new int[n2 + 1];
int i, j, k;
for (i = 0; i < n1; i++)
L[i] = a[p + i];
for (j = 0; j < n2; j++)
R[j] = a[q + j + 1];
L[n1] = 0xFFFF, R[n2] = 0xFFFF;
i = 0; j = 0;
for (k = p; k <= r; k++){
if (L[i] <= R[j])
a[k] = L[i++];
else
a[k] = R[j++];
}
}
void Merge_sort(int a[], int p, int r)
{
if (p < r){
int q = (p + r) / 2;
Merge_sort(a, p, q);
Merge_sort(a, q + 1, r);
Merge(a, p, q, r);
}
}
int main()
{
int a[] = { 4, 2, 1, 8, 5, 3, 9, 2, 0 };
int n = sizeof(a) / sizeof(a[0]);
Merge_sort(a, 0, n - 1);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}