给一个数组,如A[]={1,3,5,46,11,22,37,45,44,78,67,98},用除了冒泡排序外的任意一种方法把此数组按降序排列。java
时间: 2024-06-13 21:08:43 浏览: 69
以下是使用Java中的Arrays.sort()方法将数组按降序排列的示例代码:
```java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] A = {1, 3, 5, 46, 11, 22, 37, 45, 44, 78, 67, 98};
Arrays.sort(A);
for (int i = 0; i < A.length / 2; i++) {
int temp = A[i];
A[i] = A[A.length - 1 - i];
A[A.length - 1 - i] = temp;
}
System.out.println(Arrays.toString(A));
}
}
```
在这个示例中,我们首先使用Arrays.sort()方法将数组按升序排列。然后,我们使用一个简单的循环将数组中的元素按降序排列。最后,我们使用Arrays.toString()方法将排好序的数组打印出来。
相关问题
给一个数组,如A[]={1,3,5,46,11,22,37,45,44,78,67,98},把此数组按降序用快速排序用c++
以下是C++实现快速排序的代码,可以将给定数组按照降序排列:
```c++
#include<iostream>
using namespace std;
void quickSort(int A[], int left, int right) {
if (left >= right) {
return;
}
int i = left, j = right, pivot = A[left];
while (i < j) {
while (i < j && A[j] <= pivot) {
j--;
}
A[i] = A[j];
while (i < j && A[i] >= pivot) {
i++;
}
A[j] = A[i];
}
A[i] = pivot;
quickSort(A, left, i - 1);
quickSort(A, i + 1, right);
}
int main() {
int A[] = {1, 3, 5, 46, 11, 22, 37, 45, 44, 78, 67, 98};
int n = sizeof(A) / sizeof(A[0]);
quickSort(A, 0, n - 1);
for (int i = n - 1; i >= 0; i--) {
cout << A[i] << " ";
}
return 0;
}
```
给一个数组,如A[]={1,3,5,46,11,22,37,45,44,78,67,98},把此数组按从大到小用快速排序用c++
以下是C++实现快速排序的代码,可以将给定数组按从大到小排序:
```c++
#include <iostream>
using namespace std;
void quickSort(int arr[], int left, int right) {
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] > pivot)
i++;
while (arr[j] < pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
int main() {
int A[] = {1, 3, 5, 46, 11, 22, 37, 45, 44, 78, 67, 98};
int n = sizeof(A) / sizeof(A[0]);
quickSort(A, 0, n - 1);
cout << "Sorted array in descending order: ";
for (int i = n - 1; i >= 0; i--)
cout << A[i] << " ";
return 0;
}
```
阅读全文