数组_经典排序算法
- 选择排序
- i ~ n-1 范围上,找到最小值并放在 i 位置,然后 i+1 ~ n-1 范围上继续
- 冒泡排序
- 0 ~ i 范围上,相邻位置较大的数滚下去,最大值最终来到 i 位置,然后 0 ~ i-1 范围上继续
- 插入排序
- 0 ~ i 范围上已经有序,新来的数从右到左滑到不再小的位置上插入,然后继续
接下来,会用具体代码实现以上三种排序算法,并包含一个具体实例:
- 选择排序 (Selection Sort)
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// 交换找到的最小元素与当前元素
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
selectionSort(arr);
System.out.println("Selection Sorted array: ");
for (int i : arr) {
System.out.print(i + " ");
}
}
}
- 冒泡排序 (Bubble Sort)
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// 交换 arr[j] 和 arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println("Bubble Sorted array: ");
for (int i : arr) {
System.out.print(i + " ");
}
}
}
- 插入排序 (Insertion Sort)
public class InsertionSort {
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
// 将 arr[i] 插入到已排序部分
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6};
insertionSort(arr);
System.out.println("Insertion Sorted array: ");
for (int i : arr) {
System.out.print(i + " ");
}
}
}