Java中常用的排序算法包括:
冒泡排序(Bubble Sort)
原理:通过相邻元素的比较和交换,将较大的元素“冒泡”到数组的末尾,直至整个数组有序。
代码实现示例:
public class BubbleSort {public void sort(int[] data) {int temp;for (int i = 0; i < data.length - 1; i++) {for (int j = 0; j < data.length - 1 - i; j++) {if (data[j] > data[j + 1]) {temp = data[j];data[j] = data[j + 1];data[j + 1] = temp;}}}}}
选择排序(Selection Sort)
原理:每次从未排序的部分选择最小(或最大)的元素,放到已排序部分的末尾,直至整个数组有序。
代码实现示例:
public class SelectionSort {public void sort(int[] data) {int temp;for (int i = 0; i < data.length - 1; i++) {int position = i;for (int j = i + 1; j < data.length; j++) {if (data[j] < data[position]) {position = j;}}temp = data[i];data[i] = data[position];data[position] = temp;}}}
插入排序(Insertion Sort)
原理:将数组分为已排序和未排序两部分,每次从未排序部分取出一个元素,插入到已排序部分的正确位置。
代码实现示例:

public class InsertSort {public void sort(int[] data) {int temp;for (int i = 1; i < data.length; i++) {for (int j = i; j > 0 && data[j] < data[j - 1]; j--) {temp = data[j];data[j] = data[j - 1];data[j - 1] = temp;}}}}
希尔排序(Shell Sort)
原理:插入排序的一种改进,通过设置递减的增量序列对数组进行多轮插入排序,最终达到完全有序。
代码实现示例:
public class ShellSort {public void sort(int[] data) {int gap = data.length / 2;while (gap > 0) {for (int i = gap; i < data.length; i++) {int temp = data[i];int j = i;while (j >= gap && data[j - gap] > temp) {data[j] = data[j - gap];j -= gap;}data[j] = temp;}gap /= 2;}}}
快速排序(Quick Sort)
原理:通过选择一个基准元素,将数组分为两部分,一部分包含小于基准的元素,另一部分包含大于基准的元素,然后递归地对这两部分进行排序。
代码实现示例:
public class QuickSort {public void sort(int[] data, int low, int high) {if (low < high) {int pivotIndex = partition(data, low, high);quickSort(data, low, pivotIndex - 1);quickSort(data, pivotIndex + 1, high);}}private int partition(int[] data, int low, int high) {int pivot = data[low];while (low < high) {while (low < high && data[high] >= pivot) {high--;}data[low] = data[high];while (low < high && data[low] <= pivot) {low++;}data[high] = data[low];}data[low] = pivot;return low;}}
归
