JAVA中使用折半查找在有序数组中插入一个元素代码

/*
	在一个有序的数组中插入一个元素
*/

class ArrayInsert
{
	public static void main(String[] args) 
	{

		int[] arr = new int[]{1,6,9,11,18,54,60,66,90};
		System.out.println("insert 19 to array:");
		printArr(arr);
		int[] newArr = insert( arr, 19 );
		printArr( newArr );

	}//end of method main

	//打印一个数组
	public static void printArr(int[] arr)
	{
		for (int x = 0; x<arr.length; x++ )
		{
			if (x == arr.length - 1)
			{
				System.out.println(arr[x]);
				break;
			}
			System.out.print(arr[x] + "\t");
		}
	}//end of method printArr

	//在数组中插入一个元素
	public static int[] insert( int[] arr, int insertKey )
	{
	
	int loc, mid;
	int[] newArr = new int[arr.length + 1];

	mid = locFind( arr, insertKey );

	//插入新元素操作,分三种情况,在首部,在尾部,在中间
	if (insertKey < arr[0])//在首部
	{
		newArr[0] = insertKey;
		for ( int x = 1; x <= arr.length; x++ )
		{
			newArr[x] = arr[x - 1];
		}
	}
	else if (insertKey > arr[arr.length - 1])//在尾部
	{
		int x;
		for (x = 0 ; x < arr.length ; x++ )
		{
			newArr[x] = arr[x];
		}
		newArr[x] = insertKey;
	}
	else//在中间
	{
		for ( loc = 0; loc <= mid; loc++ )//插入位之前的元素赋值给新数组
		{
			newArr[loc] = arr[loc];
		}

		newArr[loc] = insertKey;
		
		for ( loc++; loc < newArr.length; loc++ )//插入位之后的元素赋值给新数组
		{
			newArr[loc] = arr[loc - 1];
		}

	}

	return newArr;

	}//end of method insert


	//用折半查找法找到元素应该插入数组的位置并返回
	public static int locFind( int[] arr, int insertKey )
	{

	int min, mid, max;

	min = 0;
	max = arr.length;
	mid = ( max + min ) / 2;

	while ( min < max )
	{
		if ( insertKey > arr[mid] )
		{
			min = mid + 1;
		}
		else if ( insertKey < arr[mid] )
		{
			max = mid - 1;
		}

		mid = ( max + min ) / 2;
	}//end of while

	return mid;

	}//end of method locFind
}//end of class ArrayInsert

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值