【问题标题】:How to use selection sort in objects and classes如何在对象和类中使用选择排序
【发布时间】:2019-04-12 12:48:05
【问题描述】:

我正在创建两个名为秒表和随机数的类,我已经完成了,但我需要创建一个测试程序来测量使用选择排序对 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】:

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

代码存在多个问题:

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

numbers.createArray(new int[numbers.getSize()]) 提供selectionSort 编译并最终对数组进行排序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2021-06-13
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    相关资源
    最近更新 更多