数据结构给一个数组,如A[]={1,3,5,46,11,22,37,45,44,78,67,98},用除了冒泡排序外的任意一种方法把此数组按降序排列。Java
时间: 2024-06-13 19:08:44 浏览: 54
数据结构(JAVA)求一个含有n个整数元素的数组a0..n-1中的最大元素
以下是使用快速排序算法对给定数组按降序排列的Java代码实现:
```java
public class QuickSortDescending {
public static void main(String[] args) {
int[] A = {1, 3, 5, 46, 11, 22, 37, 45, 44, 78, 67, 98};
quickSortDescending(A, 0, A.length - 1);
System.out.println(Arrays.toString(A));
}
public static void quickSortDescending(int[] A, int left, int right) {
if (left < right) {
int pivotIndex = partition(A, left, right);
quickSortDescending(A, left, pivotIndex - 1);
quickSortDescending(A, pivotIndex + 1, right);
}
}
public static int partition(int[] A, int left, int right) {
int pivot = A[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (A[j] >= pivot) {
i++;
swap(A, i, j);
}
}
swap(A, i + 1, right);
return i + 1;
}
public static void swap(int[] A, int i, int j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
```
阅读全文