public class Sort {
public static void main(String[] args) {
int[] array = { 100, 20, 30, 10, 80, 90, 50, 70, 40, 60 };
selectSort(array);
}
public static void bubbleSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {// 最多做n-1趟排序
// 这个循环是排序的空间进行排序(j的范围很关键,这个范围是在逐步缩小的,因为每一趟排序,都会找到当前最小的移到后面)
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j] < array[j + 1]) {// 把小的值交换到后面
int temp;
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
print(i, array);
}
}
public static void selectSort(int[] array) {
for (int i = 0; i < array.length; i++) {
int minIndex = i;// 假定每次排序的第一个是最小的
for (int j = i + 1; j < array.length; j++) {// 将设定的最小值与其后每一项比较
if (array[i] > array[j]) {
minIndex = j;
int temp;
temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
print(i, array);
}
}
public static void print(int i, int[] array) {
System.out.print("第" + (i + 1) + "次排序结果:");
for (int a : array) {
System.out.print(a + "\t");
}
System.out.println();
}
}
java冒泡排序 选择排序 算法
最新推荐文章于 2022-12-10 21:20:46 发布