如何在 Java 中随机选择一种方法

How to choose a method randomly in Java

我在 class

中有几种排序和搜索方法
public static void MetodoBurbuja(int[] A) {
    int i, j, aux;

    for (i = 0; i < A.length - 1; i++) {
        for (j = 0; j < A.length - i - 1; j++) {
            if (A[j + 1] < A[j]) {
                aux = A[j + 1];
                A[j + 1] = A[j];
                A[j] = aux;
            }
        }
    }
}

public static void MetodoBurbujaOptimizada(int vector[]) {
    int aux, i, j;
    for (i = 0; i < vector.length; i++) {
        for (j = 0; j < i; j++) {
            if (vector[i] < vector[j]) {
                aux = vector[j];
                vector[j] = vector[i];
                vector[i] = aux;
            }
        }
    }
}

并使用变量 metbu 从主 class 调用它们。

public static void main(String[] args) throws IOException {
    
    //llamamos al metodo burbuja
    metodoburbuja2 metbu = new metodoburbuja2();

    for(int i = 0; i < ejec; i++){
    
        int [] inputTenThousand = new int [500000];
        int n = inputTenThousand.length;
        for (int a = 0; a < inputTenThousand.length; a++){
        
            inputTenThousand [a] = (int) (Math.random() * 500000);
            
        }
        
        long time_start, time_end;
        time_start = System.nanoTime(); 

       metbu.MetodoBurbujaOptimizada(inputTenThousand);

        time_end = System.nanoTime();
        
        nanosec = time_end - time_start;
        milsec = nanosec * 0.000001;
        System.out.print(milsec + " ");

    }
    

你怎么能随机选择所有这些方法中的一种?

任何批评,帮助或建议,我将不胜感激,因为你没有想法

您可以使用另一个 Math.random() 语句通过 if 语句在两种方法之间随机选择

所以不仅仅是单独调用:

metbu.MetodoBurbujaOptimizada(inputTenThousand);

尝试使用类似的东西:

if(Math.random() > 0.5){
    System.out.println("Using MetodoBurbuja");
    metbu.MetodoBurbuja(inputTenThousand);
}
else{
    System.out.println("Using MetodoBurbujaOptimizada");
    metbu.MetodoBurbujaOptimizada(inputTenThousand);
}

希望我能正确解释你的问题!

至于其他指针,您可以使用 System.currentTimeMillis() 而不是纳秒,而不必将它们转换为毫秒。

您可以尝试的一件事是在您的 for 循环中生成一个介于 1 和您想要 运行 的算法数量之间的随机数,然后在“switch”语句中使用该数字:

package com.company;

import java.util.Random;

public class Main {
    private Random randomGenerator = new Random();
    
    public static void main(String[] args) {
        // this code would go inside your for-loop:
        int randNumber = randomGenerator.nextInt(10);
        switch(randNumber) {
            case 1:
                // call method "a" here
                break;
            case 2:
                // call method "b" here
                break;
            // and so forth
            default:
                break;
        }
    }
}