黑马程序员技术交流社区
标题:
封装的数组中元素的位置置换函数,为什么脚标越界?
[打印本页]
作者:
sandra_bae
时间:
2015-5-3 11:07
标题:
封装的数组中元素的位置置换函数,为什么脚标越界?
class Select
{
public static void swap(int[] arr,int a,int b)
{
int temp = arr[a]; //运行时,脚标越界
arr[a] = arr[b];
arr[b] = temp;
/*arr[a] = arr[a]^arr[b];
arr[b] = arr[a]^arr[b];
arr[a] = arr[a]^arr[b];*/
}
public static void bubbleSort(int[] arr)
{
for(int x = 0; x<arr.length-1; x++)
{
for(int y = 0; y<arr.length-1-x; y++)
{
if(arr[y]>arr[y+1])
{
/*int temp = arr[y];
arr[y] = arr[y+1];
arr[y+1] = temp;*/
swap(arr,arr[y],arr[y+1]); //脚标越界
}
}
}
}
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]+"]\n");
}
}
public static void main(String[] args)
{
int[] arr = {9,8,7,6,5,4,3,2,1};
//排序前:
printArray(arr);
//排序后:
bubbleSort(arr); //脚标越界
printArray(arr);
}
}
复制代码
作者:
sandra_bae
时间:
2015-5-3 11:17
好吧,第24行应该把脚标位传进swap函数中,而不是元素,传元素,等于是把元素当脚标了。
24. swap(arr,arr[y],arr[y+1]); //脚标越界
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2