冒泡排序算法
public static void BubbleSort(int[] A, int N) {
int temp = 0;
boolean flag;
for (int j = N - 1; j > 0; j--) {
flag = true;
for (int i = 0; i < j; i++) {
if (A[i] > A[i + 1]) {
temp = A[i];
A[i] = A[i + 1];
A[i + 1] = temp;
flag = false;
}
}
if (flag) {
break;
}
}
}
插入排序
public static void InsertSort(int[] A, int N) {
int tmp, j;
for (int i = 1; i < N; i++) {
tmp = A[i];
for (j = i; j > 0 && A[j - 1] > tmp; j--) {
A[j] = A[j - 1];
}
A[j] = tmp;
}
}
选择排序
public static void selectionSort(int[] A, int N) {
int minPosition;
for (int i = 0; i < N; i++) {
minPosition = scanForMin(A, i, N - 1);
swap(A, minPosition, i);
}
}
private static void swap(int[] a, int minPosition, int i) {
int tmp = a[i];
a[i] = a[minPosition];
a[minPosition] = tmp;
}
private static int scanForMin(int[] a, int i, int N) {
int minPosition = i;
for (int j = i + 1; j <= N; j++) {
if (a[j] < a[minPosition]) {
minPosition = j;
}
}
return minPosition;
}
public static void main(String[] args) {
int[] ints = {13, 432, 4553, 322, 442, 5, 5, 0, 32,};
selectionSort(ints, ints.length);
System.out.println(Arrays.toString(ints));
}
预计今天2021-12-23 更新 插入 选择 希尔排序
|