import java.util.Arrays;
public class ArrayDemo2 {
public static void main(String[] args) {
int[] arr = { 8, 9, 1, 0, 45, 32, 51, 64, 12 };
// selectionSort(arr);
bubblingSort(arr);
}
public static void selectionSort(int[] arr) {
// 选择排序
int temp;
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
public static void bubblingSort(int[] arr) {
// 冒泡排序
for (int i = 1; i < arr.length ; i++) {
for (int k = 0; k < arr.length-i; k++) {
//如果前者a[k]大于后者a[k+1] 两者交换位置
if (arr[k]>arr[k+1]) {
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
冒泡排序和选择排序
最新推荐文章于 2024-08-24 17:09:16 发布