使用Java在[10 30]范围内随机10个数字存入数组,通过快速排序进行降序排列,统计下该数组中每个元素的个数,去掉该数组中重复元素
时间: 2024-02-16 11:03:20 浏览: 69
好的,让我来回答你的问题。
首先,我们可以使用Java的Random类在[10, 30]范围内生成10个随机数,并存入数组中。代码如下:
```java
import java.util.Arrays;
import java.util.Random;
public class Main {
public static void main(String[] args) {
int[] arr = new int[10];
Random rand = new Random();
for (int i = 0; i < 10; i++) {
arr[i] = rand.nextInt(21) + 10;
}
System.out.println("原始数组:");
System.out.println(Arrays.toString(arr));
}
}
```
接下来,我们可以使用快速排序对数组进行排序。代码如下:
```java
import java.util.Arrays;
import java.util.Random;
public class Main {
public static void main(String[] args) {
int[] arr = new int[10];
Random rand = new Random();
for (int i = 0; i < 10; i++) {
arr[i] = rand.nextInt(21) + 10;
}
System.out.println("原始数组:");
System.out.println(Arrays.toString(arr));
quickSort(arr, 0, arr.length - 1);
System.out.println("排序后数组:");
System.out.println(Arrays.toString(arr));
}
private static void quickSort(int[] arr, int left, int right) {
if (left < right) {
int pivot = partition(arr, left, right);
quickSort(arr, left, pivot - 1);
quickSort(arr, pivot + 1, right);
}
}
private static int partition(int[] arr, int left, int right) {
int pivot = arr[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (arr[j] > pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[right];
arr[right] = temp;
return i + 1;
}
}
```
最后,我们可以使用HashMap统计数组中每个元素的个数,并去掉重复元素。代码如下:
```java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Main {
public static void main(String[] args) {
int[] arr = new int[10];
Random rand = new Random();
for (int i = 0; i < 10; i++) {
arr[i] = rand.nextInt(21) + 10;
}
System.out.println("原始数组:");
System.out.println(Arrays.toString(arr));
quickSort(arr, 0, arr.length - 1);
System.out.println("排序后数组:");
System.out.println(Arrays.toString(arr));
Map<Integer, Integer> map = new HashMap<>();
for (int i : arr) {
if (map.containsKey(i)) {
map.put(i, map.get(i) + 1);
} else {
map.put(i, 1);
}
}
System.out.println("去重后元素个数:");
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
private static void quickSort(int[] arr, int left, int right) {
if (left < right) {
int pivot = partition(arr, left, right);
quickSort(arr, left, pivot - 1);
quickSort(arr, pivot + 1, right);
}
}
private static int partition(int[] arr, int left, int right) {
int pivot = arr[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (arr[j] > pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[right];
arr[right] = temp;
return i + 1;
}
}
```
希望能够帮到你。
阅读全文