用Java实现常见排序算法详解
排序算法是计算机科学中最基础也是最重要的算法之一。本文将介绍几种常见的排序算法,并用Java语言实现它们。
一、排序算法概述
排序算法可以分为两大类:
- 比较类排序:通过比较来决定元素间的相对次序,其时间复杂度不能突破O(nlogn)
- 非比较类排序:不通过比较来决定元素间的相对次序,可以突破基于比较排序的时间下界
本文将重点介绍以下几种排序算法:
- 冒泡排序
- 选择排序
- 插入排序
- 快速排序
- 归并排序
- 堆排序
二、各排序算法实现
1. 冒泡排序(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("排序后的数组:");for (int num : arr) {System.out.print(num + " ");}}
}
时间复杂度:O(n²)
2. 选择排序(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</