Class 如何在对象和类中使用选择排序
我正在创建两个名为秒表和随机数的类,我已经完成了,但是我需要创建一个测试程序来测量使用选择排序对100000个数字进行排序的执行时间。我知道如何创建选择排序,我只是不知道如何使用随机数类并将其与选择排序组合在一起,我得到错误消息“不兼容类型随机数无法转换为int”,希望有人能帮助我 我的随机数课Class 如何在对象和类中使用选择排序,class,sorting,random,numbers,Class,Sorting,Random,Numbers,我正在创建两个名为秒表和随机数的类,我已经完成了,但是我需要创建一个测试程序来测量使用选择排序对100000个数字进行排序的执行时间。我知道如何创建选择排序,我只是不知道如何使用随机数类并将其与选择排序组合在一起,我得到错误消息“不兼容类型随机数无法转换为int”,希望有人能帮助我 我的随机数课 import java.util.Random; public class randomnumbers { Random ran1 = new Random(); private int size
import java.util.Random;
public class randomnumbers {
Random ran1 = new Random();
private int size;
public randomnumbers(){
size = 100000;
}
public int getSize(){
return size;
}
public void setSize(int newSize){
size = newSize;
}
public int [] createArray(int [] size){
for (int i = 0; i < size.length; i++){
size[i] = ran1.nextInt();
}
return size;
}
public static void printArray (int [] array){
for (int i = 0; i < array.length; i++){
if (i < 0){
System.out.println(array[i] + " ");
}
}
}
}
import java.util.Random;
公共类随机数{
Random ran1=新的Random();
私有整数大小;
公众电话号码(){
规模=100000;
}
公共int getSize(){
返回大小;
}
公共无效设置大小(int newSize){
大小=新闻大小;
}
公共int[]创建数组(int[]大小){
对于(int i=0;i
我的测试程序
public static void main (String [] args){
// Create a StopWatch object
StopWatch timer = new StopWatch();
//create random numbers
randomnumbers numbers = new randomnumbers();
//Create the size of the array
numbers.getSize();
// Invoke the start method in StopWatch class
timer.start();
//sort random numbers
selectionSort();
// Invoke the stop method in StopWatch class
timer.stop();
// Display the execution time
System.out.println("The execution time for sorting 100,000 " +
"numbers using selection sort: " + timer.getElapsedTime() +
" milliseconds");
}
// selectionSort performs a selection sort on an array
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int min = array[i];
int minIndex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < min) {
min = array[j];
minIndex = j;
}
}
if (i != minIndex) {
array[minIndex] = array[i];
array[i] = min;
}
}
}
}
publicstaticvoidmain(字符串[]args){
//创建秒表对象
秒表计时器=新秒表();
//创建随机数
随机数=新的随机数();
//创建数组的大小
getSize();
//在StopWatch类中调用start方法
timer.start();
//对随机数排序
selectionSort();
//在StopWatch类中调用stop方法
timer.stop();
//显示执行时间
System.out.println(“排序100000的执行时间”+
“使用选择排序的数字:”+timer.getElapsedTime()+
“毫秒”);
}
//selectionSort对数组执行选择排序
公共静态void selectionSort(int[]数组){
对于(inti=0;i
您从哪里得到“不兼容类型随机数无法转换为int”错误
该代码存在多个问题:
size
字段在randomnumbers
类中用作构造函数中的实际数组大小,但在createArray
中,它被一个名称相同但类型和含义不同的参数所掩盖Main
中的selectionSort
传递任何数组。这就是我在你的代码中得到编译错误的地方使用
numbers.createArray(新int[numbers.getSize()])输入selectionSort
。请正确缩进代码。这真的很重要!