#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
const char INFILE[]="IntegerArray.txt";
long RTN_LNUM()
{
FILE*fp = fopen(INFILE,"r");
long LNUM=0;
char ch[100];
while (fgets(ch,100,fp))
LNUM++;
fclose(fp);
return LNUM;
}
long* FETCH_DATA()
{
long LinNum=RTN_LNUM(); // Scan the file and return the line number
FILE*fp = fopen(INFILE,"r");
long* data; // Store the input data
char ch[100];
long i=0;
data = (long*)calloc(LinNum,sizeof(long));
for (i=0; i<LinNum; i++) {
fgets(ch,100,fp);
data[i]=atoi(ch);
}
fclose(fp);
return data;
}
long CountSplitInv(long* data, long p, long q)
{
long *left,*right;
long i,j,k,r,z;
z=0; // z is the returned value of inversion numbers
r=(p+q)/2+1; // r is the place where the second array starts
left = (long*)calloc(r-p+1,sizeof(long));
right = (long*)calloc(q-r+2,sizeof(long));
for (k=0; k<r-p; k++)
left[k]=data[p+k];
left[r-p]=1000001;
for (k=0; k<q-r+1; k++)
right[k]=data[r+k];
right[q-r+1]=1000001;
i=0; j=0; // init the two arrays
for (k=p; k<q+1; k++) {
if (left[i]<right[j])
data[k]=left[i++];
else {
data[k]=right[j++];
z = z+(r-p-i);
}
}
return z;
}
long SortAndCount(long* data, long p, long q)
{
long x,y,z;
long i;
if (p==q)
return 0;
else {
x = SortAndCount(data,p,(p+q)/2);
y = SortAndCount(data,(p+q)/2+1,q);
z = CountSplitInv(data,p,q);
return x+y+z;
}
}
void main()
{
long * data = FETCH_DATA();
printf("InvNum = %ld\n",SortAndCount(data,0,RTN_LNUM()-1));
}
Programming Question-1-Inversion Numbers
最新推荐文章于 2021-08-30 20:44:59 发布