我自己考自己的一道题,考到最后我都不知道怎么回事了..结果跟我想的不一样,是不是数组赋值那出问题了?求大神帮看下,我刚学,是不是俩数组不能这样赋值?
运行结果是这个..
[5,6,7,7,23,46,54,56,68,98,323,435]
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
//定义一个数组{23,435,56,5,54,46,6,7,68,7,9,8,323}
//把它排序并且找到元素46的位置,用折半查找法
public class Test10
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int[] arr = {23,435,56,5,54,46,6,7,68,7,98,323};
bubbleSort(arr);//冒泡法排序
printArray(arr);//打印排序后的数组
System.out.println();
int[] arr2 = new int[30];//定义一个新数组
arrayToArray(arr, arr2);//把arr中的元素赋值给arr2
halfSearch(arr2, 46);//折半查找
}
public static void bubbleSort(int[] arr)//冒泡排序
{
for(int x = 0; x < arr.length-1; x++)
{
for(int y = 0; y <arr.length-x-1;y++)
{
if(arr[y] > arr[y+1])
{
int temp = arr[y];
arr[y] = arr[y+1];
arr[y+1] = temp;
}
}
}
}
public static void printArray(int[] arr)//打印数组
{
System.out.print("[");
for(int x=0; x < arr.length; x++)
{
if(x!=arr.length-1)
System.out.print(arr[x] + ",");
else
System.out.print(arr[x] + "]");
}
}
public static int halfSearch(int[] arr,int key)//折半查找
{
int min = 0, max = arr.length-1, mid = (min + max)/2;
while(arr[mid]!=key)
{
if(key > arr[mid])
min = mid+1;
else if(key < arr[mid])
max = mid-1;
if(min > max)
return -1;
mid = (min+max)/2;
}
System.out.print("-----------");
return mid;
}
public static void arrayToArray(int[] arr1, int[] arr2)//互换数组元素
{
for(int x = 0; x < arr1.length; x++)
{
arr1[x] = arr2[x];
}
printArray(arr2);
}
}
|