问题是要使用给定的大整数数组文件中的归并排序来计算反转次数。虽然我可以编写用于反转计数的代码,但无法编写如何读取和打印给定文件的反转次数。有什么帮助吗?
long Merge(int arr[], int temp[], int low, int mid, int high)
{
int k = low, i = low, j = mid + 1;
long inversionCount = 0;
while (i <= mid && j <= high)
{
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
}
else {
temp[k++] = arr[j++];
inversionCount += (mid - i + 1);
}
}
while (i <= mid)
temp[k++] = arr[i++];
for (int i = low; i <= high; i++)
arr[i] = temp[i];
return inversionCount;
}
long MergeSort(int arr[], int temp[], int low, int high)
{
if (high == low)
return 0;
int mid = (low+high)/2;
long inversionCount = 0;
inversionCount = inversionCount + MergeSort(arr, temp, low, mid);
inversionCount =inversionCount + MergeSort(arr, temp, mid + 1, high);
inversionCount =inversionCount + Merge(arr, temp, low, mid, high);
return inversionCount;
int main()
{
FILE *in_file;
int arr[1000000000];
int N = sizeof(arr)/sizeof(arr[0]);
int temp[N];
for (int i = 0; i < N; i++)
temp[i] = arr[i];
in_file = fopen("integerarray.txt", "r");
if(in_file == NULL){
printf("Error");}
else{
printf("Inversion Count is %ld", mergesort(arr, temp, 0, N - 1));
return 0;
}
}
收到未定义mergesort的错误。