在Java中,可以使用不同的方法来对数组或集合进行从大到小的排序。以下是一些常见的排序方法:
1. 冒泡排序(Bubble Sort):两两比较相邻元素,如果顺序错误就交换它们,依次重复直到整个数组排序完成。这种方法可以直接在原始数组上进行排序。
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; } } } }
2. 选择排序(Selection Sort):每次循环找到未排序部分中的最大元素,然后将其放置到已排序部分的开头。这种方法需要使用额外的空间来存储已排序的子数组。
public static void selectionSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { int maxIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] > arr[maxIndex]) { maxIndex = j; } } // 交换arr[i]和arr[maxIndex] int temp = arr[i]; arr[i] = arr[maxIndex]; arr[maxIndex] = temp; } }
3. 插入排序(Insertion Sort):将未排序的元素依次插入到已排序部分的正确位置。类似于打牌时按顺序插入卡牌。
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; } }
4. 快速排序(Quick Sort):选取一个基准元素,将数组分为两个子数组,一个包含比基准元素大的元素,一个包含比基准元素小的元素,然后递归对子数组进行排序。
public static void quickSort(int[] arr, int low, int high) { if (low < high) { int pivotIndex = partition(arr, low, high); quickSort(arr, low, pivotIndex - 1); quickSort(arr, pivotIndex + 1, high); } } public static int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] >= pivot) { i++; // 交换arr[i]和arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // 交换arr[i+1]和arr[high] int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; }
以下是使用这些排序方法对数组从大到小进行排序的示例:
int[] arr = {5, 2, 8, 1, 9}; bubbleSort(arr); // or selectionSort(arr); // or insertionSort(arr); // or quickSort(arr, 0, arr.length - 1); System.out.println("从大到小排列:"); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }
输出结果为:
从大到小排列: 9 8 5 2 1
版权申明:财旺号所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流,不声明或保证其内容的正确性,如发现本站有涉嫌抄袭侵权/违法违规的内容。请发送邮件至 1790309299@qq.com 举报,一经查实,本站将立刻删除。