分析:
插入前:二分查找法确定位置。插入时:因为是静态数组(未使用容器,无法动态扩容),因此插入时必须将插入点之后的元素都往后移动一个位置,最后将该元素赋值到该位置。按顺序输出即可。
C#代码如下:
//Binary Search and insert the number
using System;
class Program
{
public static int BinarySearch(int[] arr, int low, int high, int target)
{
int mid = (low + high) / 2;
if (low > high)
return low;
else
{
if (arr[mid] == target)
return mid;
else if (arr[mid] > target)
return BinarySearch(arr, low, mid - 1, target);
else
return BinarySearch(arr, mid + 1, high, target);
}
}
public static void ArrPrint(int[] arr)
{
foreach (int elem in arr)
{
Console.Write(elem + " ");
}
}
public static int[] InsertElement(int[] arr, int pos, int target)
{
int[] arr_new = new int[arr.Length + 1];
for (int i = 0, j = 0; i < arr_new.Length; ++i)
{
if (i == pos)
arr_new[i] = target;
else
arr_new[i] = arr[j++];
}
return arr_new;
}
static void Main()
{
Random r = new Random();
int[] arr = new int[10];
for (int i = 0; i < arr.Length;++i )
{
arr[i] = r.Next(1, 100);
}
Array.Sort(arr);
Console.Write("\nThe original array:\t");
ArrPrint(arr);
Console.WriteLine("\n\nPlease enter the element you want to insert:");
int target = Convert.ToInt32(Console.ReadLine());
int location = BinarySearch(arr, 0, arr.Length - 1, target);
Console.Write("\nThe inserted array:\t");
int[] arr_new = InsertElement(arr, location, target);
ArrPrint(arr_new);
}
}
运行结果