Java数组的冒泡排序和选择排序实现代码
冒泡排序
@Test
public void testArraySort() {
int[] arr = {123,3,4,5,623,654,678,34,34,0,-123,-33};
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1; j++) {
if(arr[j] > arr[j + 1]){
arr[j] = arr[j + 1] ^ arr[j];
arr[j + 1] = arr[j + 1] ^ arr[j];
arr[j] = arr[j + 1] ^ arr[j];
}
}
}
System.out.println(Arrays.toString(arr));
}
选择排序
// 选择排序
@Test
public void testArraySort2() {
int[] arr = {123,3,4,5,623,654,678,34,34,0,-123,-33};
int tempIdx = 0;
for (int i = 0; i < arr.length - 1; i++) {
tempIdx = i;
for (int j = i + 1; j < arr.length; j++) {
if(arr[tempIdx] > arr[j]){
tempIdx = j;
}
}
if(tempIdx != i){
arr[i] = arr[tempIdx] ^ arr[i];
arr[tempIdx] = arr[tempIdx] ^ arr[i];
arr[i] = arr[tempIdx] ^ arr[i];
}
}
System.out.println(Arrays.toString(arr));
}