在Java中,你可以使用多种排序算法对数据进行排序。下面是一些常用的排序方法及其Java实现:
冒泡排序(Bubble Sort)
冒泡排序是一种简单的排序算法,通过重复遍历待排序的列表,比较相邻元素并交换位置,使得每一趟遍历后最大的元素被移动到列表的末尾。
public class BubbleSort {public static void sort(int[] array) {for (int i = 0; i < array.length - 1; i++) {for (int j = 0; j < array.length - 1 - i; j++) {if (array[j] > array[j + 1]) {int temp = array[j];array[j] = array[j + 1];array[j + 1] = temp;}}}}}
选择排序(Selection Sort)
选择排序每次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。
public class SelectionSort {public static void sort(int[] array) {for (int i = 0; i < array.length - 1; i++) {int minIndex = i;for (int j = i + 1; j < array.length; j++) {if (array[j] < array[minIndex]) {minIndex = j;}}int temp = array[minIndex];array[minIndex] = array[i];array[i] = temp;}}}
插入排序(Insertion Sort)

插入排序的工作方式是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
public class InsertionSort {public static void sort(int[] array) {for (int i = 1; i < array.length; i++) {int key = array[i];int j = i - 1;while (j >= 0 && array[j] > key) {array[j + 1] = array[j];j = j - 1;}array[j + 1] = key;}}}
快速排序(Quick Sort)
快速排序是一种分治算法,通过选择一个基准值(pivot)将要排序的数组分割成两个子数组,一个子数组的所有元素都比基准值小,另一个子数组的所有元素都比基准值大,然后递归地对这两个子数组进行排序。
public class QuickSort {public static void sort(int[] array, int low, int high) {if (low < high) {int pi = partition(array, low, high);sort(array, low, pi - 1);sort(array, pi + 1, high);}}private static int partition(int[] array, int low, int high) {int pivot = array[high];int i = (low - 1);for (int j = low; j < high; j++) {if (array[j] < pivot) {i++;int temp = array[i];array[i] = array[j];array[j] = temp;}}int temp = array[i + 1];array[i + 1] = array[high];array[high] = temp;return i + 1;}}
归并排序(Merge Sort)
归并排序也是一种分治算法,将数组分成两半,分别对它们进行排序,然后将结果合并起来。
