排序算法是 蓝桥杯 Java B 组的高频考点,主要考察:
思想:
时间复杂度
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+1] 和 arr[j]
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);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
思想:
时间复杂度
import java.util.Arrays;
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[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
selectionSort(arr);
System.out.println(Arrays.toString(arr));
}
}
思想:
时间复杂度
import java.util.Arrays;
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;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j]; // 后移
j--;
}
arr[j + 1] = key; // 插入合适位置
}
}
public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6};
insertionSort(arr);
System.out.println(Arrays.toString(arr));
}
}
输入一个数组,求前 K 大的元素。
输入:arr = [3, 1, 5, 6, 2, 8, 7], K = 3
输出:[8, 7, 6]
import java.util.Arrays;
public class TopK {
public static int[] topK(int[] arr, int k) {
Arrays.sort(arr); // 默认升序
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = arr[arr.length - 1 - i]; // 取最大的 k 个
}
return result;
}
public static void main(String[] args) {
int[] arr = {3, 1, 5, 6, 2, 8, 7};
System.out.println(Arrays.toString(topK(arr, 3)));
}
}
import java.util.PriorityQueue;
public class TopKHeap {
public static int[] topK(int[] arr, int k) {
PriorityQueue minHeap = new PriorityQueue<>();
for (int num : arr) {
minHeap.add(num);
if (minHeap.size() > k) {
minHeap.poll(); // 维持小顶堆
}
}
int[] result = new int[k];
for (int i = k - 1; i >= 0; i--) {
result[i] = minHeap.poll();
}
return result;
}
public static void main(String[] args) {
int[] arr = {3, 1, 5, 6, 2, 8, 7};
System.out.println(Arrays.toString(topK(arr, 3)));
}
}
考点 |
典型题目 |
难点 |
冒泡排序 |
手写冒泡排序 |
优化提前终止 |
选择排序 |
找第 K 小的数 |
减少交换次数 |
插入排序 |
手写插入排序 |
插入位置的查找 |
Top K 问题 |
求前 K 大/小 |
使用堆优化 |
✅ 冒泡排序未优化
if (!swapped) break; // ✅ 提前终止
✅ Arrays.sort(arr) 默认是升序 ✅ PriorityQueue 默认是小顶堆
PriorityQueue
✅ 排序后索引变化
arr.sort((a, b) -> b - a); // ✅ 降序
✅ 自己手写排序代码,理解内部逻辑
✅ 练习求 Top K 问题,熟悉 PriorityQueue
✅ 分析时间复杂度,选择合适排序方法