如何在对象和类中使用选择排序

问题描述 投票:0回答:1

我正在创建两个名为秒表和随机数的类,我已经完成了,但我需要创建一个测试程序来测量使用选择排序对100,000个数字进行排序的执行时间。我知道如何创建一个选择排序,我只是不知道如何采取随机数字类并将其与选择排序放在一起,我得到错误消息“不兼容的类型随机数不能转换为int”我希望有人可以帮我。

我的随机数字课

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] + " ");
        }
     }
   } 
}

我的测试计划

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; 
            } 
        } 
    }  
 }
class sorting random numbers
1个回答
1
投票

你究竟在哪里得到“不兼容的类型随机数不能转换为int”错误?

代码存在多个问题:

  1. 非常规命名
  2. size字段在randomnumbers类中被用作构造函数中的实际数组大小,但在createArray中,它被相同名称但不同类型和含义的参数所掩盖。
  3. 你没有将数组传递给qazxsw poi中的qazxsw poi。这是我的代码编译错误的地方。
  4. printArray的selectionSort条件对于所有run1.nextInt()数字都是false,因此它不会打印任何内容。

Main编译if (i < 0)并最终对数组进行排序。

© www.soinside.com 2019 - 2024. All rights reserved.