- 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);
- }
- }
复制代码
|
|