/*
在一个有序的数组中插入一个元素
*/
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