一、冒泡排序
/**
* @author liyong
* @date 2021年12月02日 23:33
*/
public class BubbleSort {
public static void main(String[] args) {
int a[] = {6, 3, 8, 2, 9, 1};
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
//排序后的数组顺序为
for (int res : a) {
System.out.print(" " + res);
}
}
}
二、选择排序
/**
* @author liyong
* @date 2021年12月02日 23:39
*/
public class SelectSort {
public static void main(String[] args) {
int a[] = {6, 3, 8, 2, 9, 1};
//外层控制总共要进行排序的趟数
for (int x = 0; x < a.length - 1; x++) {
//内层表示要和下标为X的数据比较数组值
for (int y = x + 1; y < a.length; y++) {
if (a[x] > a[y]) {
int temp = a[y];
a[y] = a[x];
a[x] = temp;
}
}
}
//排序后的数组顺序为
for (int res : a) {
System.out.print(" " + res);
}
}
}
三、插入排序
/**
* @author liyong
* @date 2021年12月02日 23:42
*/
public class InsertionSort {
public static void main(String[] args) {
int a[] = {6, 8, 2, 4, 1, 6, 3};
//N个数,则需要进行n-1次排序
//从第一个元素开始,该元素可以认为已经被排序
for (int i = 0; i < a.length - 1; i++) {
//取出下一个元素,在已经排序的元素序列中从后向前扫描
for (int j = i + 1; j > 0; j--) {
//如果该元素(已排序)大于新元素,将该元素移到下一位置
if (a[j] < a[j - 1]) {
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
//重新输出
for (int res : a
) {
System.out.print(" " + res);
}
}
}