用Java随机生成10000不含重复的整数,用选择排序对其从小到大排序并记录运行时间(分三种情况:有序,逆序,随机排序),先分析算法时间复杂度,再比较实际运行时间
时间: 2023-03-26 16:00:29 浏览: 187
选择排序的时间复杂度为O(n^2),其中n为待排序数组的长度。对于有序和逆序数组,选择排序的时间复杂度仍为O(n^2),因为每次比较都需要进行n-1次,而交换次数为和n-1次。对于随机排序的数组,选择排序的时间复杂度仍为O(n^2),因为每次比较都需要进行n-1次,而交换次数为到n-1次。
我可以回答你的问题。以下是Java代码:
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] arr = generateRandomArray(10000);
long startTime = System.currentTimeMillis();
selectionSort(arr);
long endTime = System.currentTimeMillis();
System.out.println("随机排序用时:" + (endTime - startTime) + "ms");
arr = generateSortedArray(10000);
startTime = System.currentTimeMillis();
selectionSort(arr);
endTime = System.currentTimeMillis();
System.out.println("有序排序用时:" + (endTime - startTime) + "ms");
arr = generateReverseArray(10000);
startTime = System.currentTimeMillis();
selectionSort(arr);
endTime = System.currentTimeMillis();
System.out.println("逆序排序用时:" + (endTime - startTime) + "ms");
}
public static int[] generateRandomArray(int n) {
Set<Integer> set = new HashSet<>();
Random random = new Random();
while (set.size() < n) {
set.add(random.nextInt());
}
int[] arr = new int[n];
int i = ;
for (int num : set) {
arr[i++] = num;
}
return arr;
}
public static int[] generateSortedArray(int n) {
int[] arr = new int[n];
for (int i = ; i < n; i++) {
arr[i] = i;
}
return arr;
}
public static int[] generateReverseArray(int n) {
int[] arr = new int[n];
for (int i = ; i < n; i++) {
arr[i] = n - i - 1;
}
return arr;
}
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = ; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
}
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)