为什么插入后原来的数组不会发生改变!?
/*
面试题:
给定一个有序的数组,如果往该数组中存储一个元素,并保证这个数组还是有序的,
那么这个元素的存储的角标该如何获取。
*/
import java.util.Arrays;
class ArrayDemo4
{
public static void main(String[] args)
{
int[] arr = {13, 15, 19, 28, 33, 45, 78, 106};
int index = halfSearch(arr, 50);
System.out.println(Arrays.toString(arr));
insert(arr, index, 50);
System.out.println(Arrays.toString(arr));
}
public static int halfSearch(int[] arr, int key)
{
int max, min, mid;
min = 0;
max = arr.length-1;
mid = 0;
while(min <= max)
{
mid = (max+min) >> 1;//相当于除2
if(key < arr[mid])
max = mid-1;
else if(key > arr[mid])
min = mid+1;
else
return mid;
}
return min;
}
public static void insert(int[] arr, int index, int num)
{
arr = Arrays.copyOf(arr, arr.length+1);//对数组进行扩充
for(int i = arr.length-1; i > index; i--)
{
arr[i] = arr[i-1];
}
arr[index] = num;
System.out.println(Arrays.toString(arr));
}
}
[解决办法]
import java.util.Arrays;
class ArrayDemo4 {
static int[] arr = { 13, 15, 19, 28, 33, 45, 78, 106 };
public static void main(String[] args) {
int index = halfSearch(50);
System.out.println(Arrays.toString(arr));
insert(index, 50);
System.out.println(Arrays.toString(arr));
}
public static int halfSearch(int key) {
int max, min, mid;
min = 0;
max = arr.length - 1;
mid = 0;
while (min <= max) {
mid = (max + min) >> 1;// 相当于除2
if (key < arr[mid])
max = mid - 1;
else if (key > arr[mid])
min = mid + 1;
else
return mid;
}
return min;
}
public static void insert(int index, int num) {
arr = Arrays.copyOf(arr, arr.length + 1);// 对数组进行扩充
for (int i = arr.length - 1; i > index; i--) {
arr[i] = arr[i - 1];
}
arr[index] = num;
System.out.println(Arrays.toString(arr));
}
}
[解决办法]
亲 有你那么麻烦吗?
public class Test {
public static void main(String[] args) {
int[] arr = {13, 15, 19, 28, 33, 45, 78, 106};
int index=search(arr,14);
System.out.println(index);
}
public static int search(int[] arr,int a)
{
for(int i=0;i<arr.length;i++)
{
int index=0;
if(arr[i]>a)
{
index=i;
return index;
}
}
return arr.length;
}
}