本帖最后由 夏凡 于 2013-3-20 12:33 编辑
- /*
- 程序功能:在有序数组中插入一个元素
- */
- class ArrInsert
- {
- public static void main(String[] args)
- {
- int arr[] ={1, 2, 3, 4, 6, 7};
- System.out.print("插入前:");
- arrPrint(arr);
- insert(arr, 5);
- System.out.print("插入后:");
- arrPrint(arr);
- }
- public static void arrPrint(int arr[]) //打印数组中的元素
- {
- for(int i=0; i<arr.length; i++)
- {
- System.out.print(arr[i]+" ");
- }
- System.out.println();
- }
- public static int search(int arr[], int x) //查找插入位置
- {
- int low=0, mid, high=arr.length-1;
- while(low <= high)
- {
- mid = (low+high)/2;
- if(x < arr[mid])
- {
- high = mid-1;
- }
- else
- if(x > arr[mid])
- {
- low = mid+1;
- }
- }
- return mid;
- }
- public static void insert(int arr[], int x) //插入元素
- {
- int local=search(arr, x);
- for(int i=arr.length-1; i>=local; i--)
- {
- arr[i+1] = arr[i];
- }
- arr[local] = x;
- }
- }
复制代码 程序报错说“return mid”中的mid未初始化,求教高手应该怎么修改 |