Question 1
This file contains all of the 100,000 integers between 1 and 100,000 (inclusive) in some order, with no integer repeated.
Your task is to compute the number of inversions in the file given, where the
ith
row of the file indicates the
ith
entry of an array.
Because of the large size of this array, you should implement the fast divide-and-conquer algorithm covered in the video lectures. The numeric answer for the given input file should be typed in the space below.
So if your answer is 1198233847, then just type 1198233847 in the space provided without any space / commas / any other punctuation marks. You can make up to 5 attempts, and we'll use the best one for grading.
(We do not require you to submit your code, so feel free to use any programming language you want --- just type the final numeric answer in the following space.)
#include"stdio.h"
#include"math.h"
#include <stdlib.h>
#define MAX_INT 1000000;
#define NUM 100000
long mergeT(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];
for(int i=0;i<n1;i++)
L[i] = a[p+i];
for(int j=0;j<n2;j++)
R[j] = a[q+j+1];
L[n1] = MAX_INT;
R[n2] = MAX_INT;
i = 0;
j = 0;
long count = 0;
for(int k=p;k<r+1;k++)
{
if(L[i]<=R[j])
{
a[k] = L[i];
i++;
}
else
{
count += (long) (n1-i);
a[k] = R[j];
j++;
}
}
return count;
}
long merge(int *a,int p, int r)
{
//printf("合并排序开始:\n");
int q =0;
if(p==r)
return 0;
else if(p<r)
{
q = (int)floor((p+r)/2);
long left = merge(a,p,q);
long right = merge(a,q+1,r);
long cross = mergeT(a,p,q,r);
return left+right+cross;
}
return 0;
}
void show(int *a,int n)
{
for(int i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\n");
}
void readFromTxt(int *b)
{
FILE *fp;
char buf[7];
int ct = 0;
fp = fopen("c:\\IntegerArray.txt","r");
if(fp==NULL)
{
perror("fail to read");
exit(1);
}
while(fgets(buf,NUM,fp)!=NULL)
{
b[ct++]=strtol(buf,NULL,0);
}
printf("一共%d条记录\n",ct);
}
void main()
{
int b[NUM];
for(int i=0;i<NUM;i++)
b[i] = 0;
readFromTxt(b);
long count = merge(b,0,NUM-1);
printf("inversion的数目是:%lu.\n",count);
}
运行结果:
如果发现有什么问题,欢迎留言,多多探讨!