一、冒泡排序
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);
}
}
}
二、选择排序
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++) {
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);
}
}
}
三、插入排序
public class InsertionSort {
public static void main(String[] args) {
int a[] = {6, 8, 2, 4, 1, 6, 3};
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);
}
}
}
|