我正在尝试在 C++ 中编写合并排序函数,但是在(在 MergeSort 函数中)出现错误:
A = MergeSort (A, x);
B = MergeSort (B, y);
C = Merge(A,B,x,y);
作为从 int 到 int* 的无效转换。我究竟做错了什么?任何帮助将不胜感激!谢谢。
这是我的功能代码:
int MergeSort (int [], int);
int Merge (int [], int [], int, int);
int MergeSort (int arr[], int len) {
int x = len/2;
int y = len-x;
int i,j;
// initialize the arrays
int * A = new int [x];
int * B = new int [y];
int * C = new int [len];
// copy left and right arrays
for (i=0, j=0; i<x; i++, j++) {
A[i] = arr[j];
}
for (i=0; i<y; i++, j++) {
B[i] = arr[j];
}
A = MergeSort (A, x);
B = MergeSort (B, y);
C = Merge(A,B,x,y);
return C;
}
int Merge(int A[], int B[], int x, int y) {
int i,j,k;
i = 0; j = 0; k = 0;
int * C = new int[x+y];
while (i < x && j < y) {
if (A[i] < B[j])
C[k++] = A[i++];
else
C[k++] = B[j++];
}
if (i < x) //A is longer
C[k++] = A[i++];
if (j < y) //B is longer
C[k++] = B[j++];
return C;
}
这是我的主要功能:
int main() {
//initialize array with some values
int ar [8] = {7, 5, 9, 1, 4, 22, 11, 10};
cout<<"array:";
for (int i=0;i<8;i++)
cout<<ar[i];
cout<<endl;
//run merge sort
ar = MergeSort(ar,8);
cout<<"merged array:";
for (int i=0;i<8;i++)
cout<<arr[i];
cout<<endl;
return 0;
}