用Java 产生0到100里面100个随机数并使用冒泡排序和选择排序对这些数进行排序
时间: 2023-05-27 19:07:05 浏览: 82
以下是Java代码示例:
```java
import java.util.Random;
public class SortRandomNumbers {
public static void main(String[] args) {
int[] arr = generateRandomNumbers(100);
System.out.println("Original array:");
printArray(arr);
bubbleSort(arr);
System.out.println("Array after bubble sort:");
printArray(arr);
arr = generateRandomNumbers(100);
selectionSort(arr);
System.out.println("Array after selection sort:");
printArray(arr);
}
// Generate an array of n random integers between 0 and 100
public static int[] generateRandomNumbers(int n) {
int[] arr = new int[n];
Random rand = new Random();
for (int i = 0; i < n; i++) {
arr[i] = rand.nextInt(101);
}
return arr;
}
// Bubble sort algorithm to sort an array of integers in ascending order
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]) {
// swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Selection sort algorithm to sort an array of integers in ascending order
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// swap arr[i] and arr[minIndex]
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
// Utility method to print an array of integers
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
```
阅读全文