辅助方法交换数组中2个索引的位置
private static void swap(int[] array, int index1, int index2) {
int tmp = array[index1];
array[index1] = array[index2];
array[index2] = tmp;
}
冒泡排序
public static void bubbleSort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
swap(array, j, j + 1);
}
}
}
}
选择排序
public static void selectSort(int[] array) {
for (int i = 0; i < array.length; i++) {
int k = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[k]) {
k = j;
}
}
if (i != k) {
swap(array, i, k);
}
}
}
插入排序
public static void insertSort(int[] array) {
int current;
for (int i = 0; i < array.length - 1; i++) {
current = array[i + 1];
int preIdx = i;
while (preIdx >= 0 && current < array[preIdx]) {
array[preIdx + 1] = array[preIdx];
preIdx--;
}
array[preIdx + 1] = current;
}
}
其它排序算法
https://blog.csdn.net/m0_54608045/article/details/120805046