冒泡排序与选择排序的联系
冒泡排序的两种写法,第二种写法的变形,就是选择排序。并且第二种写法好理解些。
第一种写法:
public static void maoPai() {
int[] arr = {13, 11, 15, -11, 99, -10, 0, 22};
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - (i + 1); j++) {
if (arr[j + 1] < arr[j]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
//[-11, -10, 0, 11, 13, 15, 22, 99]
}
第二种写法:
public static void maoPai() {
int[] arr = {13, 11, 15, -11, 99, -10, 0, 22};
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i+1; j < arr.length; j++) {
if (arr[j] < arr[i]) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
//[-11, -10, 0, 11, 13, 15, 22, 99]
}
选择排序
public static void xuanPai() {
int[] arr = {13, 11, 15, -11, 99, -10, 0, 22};
for (int i = 0; i < arr.length - 1; i++) {
int index = i;
for (int j = i+1; j < arr.length; j++) {
if (arr[j] < arr[index]) {
index = j;
}
}
//比完再交换
int temp = arr[index];
arr[index] = arr[i];
arr[i] = temp;
}
System.out.println(Arrays.toString(arr));
}