简体   繁体   中英

Creating arrays with successive numbers of integers for benchmarking purposes using sorting algorithms

I am working on a benchmarking assignment for various algorithms. The requirements are to run the programs with successive data sets of random integers totaling 10,000, 20,000, 100,000, 200,000, 1,000,000 respectively. I have written the programs so that I can manually input the data set sizes, but, I would prefer to use a loop to run the program once and automatically input the different data sets. I'm not really sure how to go about doing this; any advice is appreciated. Thanks in advance.

package bubble.sort;



public class BubbleSort {

public static void main(String[] arg) throws Exception{

    int array[] = new int [1000];
    int i;

    for (int k = 1; k<= 100; k++){

        for (i=0;i<array.length;i++){
        //for loop that will populate array with random numbers 
        array[i] = 1 + (int)(Math.random() * 10);
        }//end for loop

    // get the start time in nanoseconds
    long startTime = System.nanoTime();

    //call mergesort to sort the entire array
    bubbleSort(array);

    // get the end time in nanoseconds
    long endTime = System.nanoTime();

    // calculate elapsed time in nanoseconds
    long duration = endTime - startTime;

    // print the elapsed time in seconds   (nanaoseconds/ 1 billion)
    System.out.printf("%12.8f %n", (double)duration/100000000) ;


    }
}
      public static void bubbleSort( int [ ] array){
      int temp = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 1; j < (array.length - i); j++) {
        if (array[j - 1] > array[j]) {
            temp = array[j - 1];
            array[j - 1] = array[j];
            array[j] = temp;
        }

      }
    }
  }
}

The simplest way - wrap your code with another loop:

int dataSetSizes[] = {10000, 20000, 100000, 200000, 1000000};
    for (int dataSetSize : dataSetSizes) {
        int array[] = new int[dataSetSize];
        // rest of your code
    }

Extract what is inside of your main method in to a method that takes in the size as a parameter and use that passed in size in order to create the array. Then, in main, run that method with each of the required sizes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM