测试类
| import com.example.test.algorithms.util.SortUtil; |
| import org.apache.commons.lang3.ArrayUtils; |
| |
| import java.util.Random; |
| public class TestSort { |
| private static final int N = 10; |
| public static void main(String[] args) { |
| int[] arr = new Random().ints(0, N).distinct().limit(N).toArray(); |
| System.out.println("排序前:" + ArrayUtils.toString(arr)); |
| SortUtil.bubbleSort(arr); |
| System.out.println("排序后:" + ArrayUtils.toString(arr)); |
| } |
| } |
排序算法:
| public class SortUtil { |
| |
| |
| |
| |
| |
| public static void bubbleSort(int[] arr) { |
| for (int i = 0; i < arr.length; i++) { |
| for (int j = 0; j < arr.length - i - 1; j++) { |
| if (arr[j] > arr[j + 1]) { |
| swap(arr, j, j + 1); |
| } |
| } |
| } |
| } |
| |
| public static void quickSort(int[] arr) { |
| doQuickSort(arr, 0, arr.length - 1); |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| private static void doQuickSort(int[] arr, int left, int right) { |
| if (left >= right) { |
| return; |
| } |
| int base = arr[left]; |
| int l = left; |
| int r = right; |
| while (l < r) { |
| |
| while (r > l && arr[r] > base) { |
| r--; |
| } |
| |
| while (l < r && arr[l] < base) { |
| l++; |
| } |
| |
| if (l < r) { |
| swap(arr, l, r); |
| } |
| } |
| |
| |
| arr[r] = base; |
| doQuickSort(arr, left, r - 1); |
| doQuickSort(arr, l + 1, right); |
| } |
| |
| |
| |
| |
| |
| |
| |
| public static void selectSort(int[] arr) { |
| int minIndex = 0; |
| for (int i = 0; i < arr.length; i++) { |
| minIndex = i; |
| for (int j = i; j < arr.length; j++) { |
| if (arr[j] < arr[minIndex]) { |
| minIndex = j; |
| } |
| } |
| swap(arr, i, minIndex); |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| public static void insertSort(int[] arr) { |
| for (int i = 0; i < arr.length - 1; i++) { |
| int current = arr[i + 1]; |
| int preIndex = i; |
| while (preIndex >= 0 && current < arr[preIndex]) { |
| arr[preIndex + 1] = arr[preIndex]; |
| preIndex--; |
| } |
| arr[preIndex + 1] = current; |
| } |
| } |
| |
| private static void swap(int[] arr, int i, int j) { |
| int temp = arr[j]; |
| arr[j] = arr[i]; |
| arr[i] = temp; |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)