2-路插入排序 一个简单示例

//a example of 2-way insertion sort

#include <stdio.h>
#include <stdlib.h>

int iList[] = {1, 4, 2, 12, 4, 34, 243, 11, 35};

void TwoWayInsert(int iList[], int iLen)//iLen is the length of iList
{
	int i, j;
	int first = 0;//pointer point to the first record
	int final = 0;//pointer point to the final record
	int *iTemp = NULL;

	if((iTemp = (int *) malloc(iLen * sizeof(int))) == NULL)//Dynamic allocation of space
	{
		fprintf(stderr, "allocate space error !");
		exit(1);
	}

	//printf("%d\n", sizeof(iList) / sizeof(iList[0]));because iList is a pointer, so this is wrong

    iTemp[0] = iList[0];//copy fisrt element of iList

	for(i = 1; i < iLen; i++)//start from the second
	{
		if(iList[i] >= iTemp[final])
		{
			iTemp[++final] = iList[i];
		}
		else if(iList[i] <= iTemp[first])
		{
			first = (first - i + iLen) % iLen;//first point to the end of iList firstly
			iTemp[first] = iList[i];//copy to iTemp[first]
		}
		else//insert when the element is bigger than iList[i] and smaller than iList[final]
		{//use binary sort insertion 
			int iLow, iHigh;
			int iMid;
			int iFlag;//identify the side of insertion

			if(iList[i] < iTemp[0])//make sure the value of low and high
			{
				iLow = first;
				iHigh = iLen - 1;
				iFlag = 1;
			}
			else
			{
				iLow = 0;
				iHigh = final;
				iFlag = 0;
			}
			while(iLow <= iHigh)//it must have equal signal
			{
				iMid = (iLow + iHigh) / 2;
				if(iList[i] <=  iTemp[iMid])//Does it must have equal signal?no matter 
				{
					iHigh = iMid - 1;
				}
				else
				{
					iLow = iMid + 1;
				}
			}
			//find the location to insert 
			if(iFlag == 0)
			{
				for(j = final; j >= iHigh + 1; --j)//backword the other element
				{
					iTemp[j + 1] = iTemp[j];
				}
				final++;
				iTemp[iHigh + 1] = iList[i];
			}
			else
			{
				for(j = first; j <= iHigh; j++)//forword the other element
				{
					iTemp[j - 1] = iTemp[j];
				}
				first--;
				iTemp[iHigh +  1] = iList[i];
			}
		}
	}
	
	j = 0;
	for(i = first; i < iLen; i++)
	{
		iList[j++] = iTemp[i];
	}
	for(i = 0; i <= final; i++)
	{
		iList[j++] = iTemp[i];
	}
}

int main(void)
{
	int i;
	int iLen;

	iLen = sizeof(iList) / sizeof(iList[0]);

	//printf("%d\n", iLen);

	TwoWayInsert(iList , iLen);

	for(i = 0; i < iLen; i++)
	{
		printf((i == iLen - 1) ? "%d\n" : "%d, ", iList[i]);
	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值