Programming Question-1-Inversion Numbers

#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));
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值