Derrik Antrium Derrik Antrium - 2 months ago 16
Java Question

How to double an array size using a for loop to compare selection sort performance with different array sizes?

My goal for this project was to measure the performance of selection sort using random numbers. I wanted to begin with an array size of n=100, and I wanted to double that array size up to 200,000 (n = 100 * 2, n = 200 * 2, n = 400 * 2....) I did a pretty good job of setting up my selectionSort method in a class, but I am having trouble writing a for loop that will double my array size of 100.
Here is my code:

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

}
}




public static void main(String[] args) {
int[] bigdata = new int[100];
randomFill(bigdata, 100000);
for(int i = 100; i < 200000; i *= 2){ // this is where I am having trouble
bigdata[i] = bigdata[i] * 2;}
display(bigdata);
System.out.println("Is sorted before selectionSort: " + isSorted(bigdata));
long start = System.currentTimeMillis();
selectionSort(bigdata);
display(bigdata);
long elapsed = System.currentTimeMillis() - start;
System.out.println("Is sorted after selectionSort: " + isSorted(bigdata));
System.out.println("Elapsed time in milliseconds " + elapsed);
}
}


My code in main has successfully displayed selectionSort performance for a random array with a size of 100, but I am unsure where to go next with writing a forloop to double my array "big data" up to 200000.

Answer
       public static void selectionSort(int[] data) {
      int temp;
      int j;
      int i;
      for (i = 0; i < data.length - 1; i++ ){  
          int min = i; 
          for(j = i + 1; j < data.length; j++){   
            if(data[j] < data[min])         
               min = j;
          }
          temp = data[min];   
          data[min] = data[i];
          data[i] = temp; 

       }
     }
public static void main(String[] args) {
         int[] bigdata;

                   for(int i = 100; i < 200000; i *= 2){ 
                      // Here you double the size of bigdata array
                      bigdata = new int[i];
                      // You fill the i sized array
                      randomFill(bigdata, 100000);
                      display(bigdata);
                      System.out.println("Is sorted before selectionSort: " + isSorted(bigdata));
                      long start = System.currentTimeMillis();
                      selectionSort(bigdata);
                      display(bigdata);
                      long elapsed = System.currentTimeMillis() - start;
                      System.out.println("Is sorted after selectionSort: " + isSorted(bigdata));
                      System.out.println("Elapsed time in milliseconds " + elapsed);
          }
       }