2014-01-25 4 views
0

Эта программа предназначена для сбора данных о скорости трех алгоритмов поиска (линейных, двоичных и случайных). Я тщательно протестировал каждый метод поиска, и все они работают. Я знаю, что ошибка существует в цикле for, содержащем k, но я не уверен, что и почему. Я получаю правильные результаты для линейных [0], двоичных [0] и случайных [0], но не могу получить ответ для любого другого места в массивах в цикле (что имеет смысл, так как я еще не успел еще в других местах). Однако вне цикла я не могу распечатать какую-либо часть любого из массивов.Как исправить мою программу сбора данных?

import java.util.Random; 
/*class to generate testing data*/ 
public class GenerateData{ 
    public static void main(String[] args) { 
    /*creates and runs through each power of 2 array*/ 
    for(int i=3; i < 5; i++) { 
     /*calculates a power of 2 starting at 8*/ 
     int n = (int)Math.pow(2, i); 
     /*creates an array of a power of 2 starting at 8*/ 
     int [] test = new int[n]; 
     /*generates a starting testing point for the array*/ 
     int start = 3; 
     /*fills the array with sorted testing data*/ 
     for(int j=0; j < n; j++) { 
     test[j] = start; 
     start = start + 2; 
     } 
     /*creates an array to store linear testing times*/ 
     long [] linear = new long[10]; 
     /*creates an array to store binary testing times*/ 
     long [] binary = new long[10]; 
     /*creates an array to store random testing times*/ 
     long [] random = new long[10]; 
     /*runs through the search algorithms ten times*/ 
     for(int k=0; k < 10; k++) { 
     /*generates a random number to test no larger than the largest 
      value in the array*/ 
     int queryValue = (int)Math.floor(Math.random()*(start-1)); 
     /*tests the array in each algorithm, keeping track of start and 
      end time*/ 
     long linearStartTime = System.nanoTime(); 
     int linearTest = LinearSearch.linearSearch(queryValue, test); 
     /*calculates the time for linear algorithm and adds it to 
     an array keeping track of linear algorithm run times*/ 
     linear[k] = System.nanoTime() - linearStartTime; 
     long binaryStartTime = System.nanoTime(); 
     int binaryTest = BinarySearch.binarySearch(queryValue, test); 
     /*calculates the time for binary algorithm and adds it to 
     an array keeping track of binary algorithm run times*/ 
     binary[k] = System.nanoTime() - binaryStartTime; 
     long randomStartTime = System.nanoTime(); 
     int randomTest = RandomSearch.randomSearch(queryValue, test); 
     /*calculates the time for random algorithm and adds it to 
      an array keeping track of random algorithm run times*/ 
     random[k] = System.nanoTime() - randomStartTime; 
     } 
     /*placeholder initial values for mins, maxes, and avgs*/ 
     long linMin = linear[1]; 
     long binMin = binary[1]; 
     long randMin = random[1]; 
     long linMax = linear[1]; 
     long binMax = binary[1]; 
     long randMax = random[1]; 
     long linAvg = 0; 
     long binAvg = 0; 
     long randAvg = 0; 
     /*cycles through the arrays calculating the min, max, and avg*/ 
     for(int l=0; l < 9; l++) { 
     /*calculates the avg for each algorithm array*/ 
     linAvg = linAvg + linear[l]/2; 
     binAvg = binAvg + binary[l]/2; 
     randAvg = randAvg + random[l]/2; 
     /*calculates the min for each algorithm array*/ 
     if(linear[l] < linMin) { 
      linMin = linear[l]; 
     } 
     if(binary[l] < binMin) { 
      binMin = binary[l]; 
     } 
     if(random[l] < randMin) { 
      randMin = random[l]; 
     } 
     /*calculates the max for each algorithm array*/ 
     if(linear[l] > linMax) { 
      linMax = linear[l]; 
     } 
     if(binary[l] > binMax) { 
      binMax = linear[l]; 
     } 
     if(random[l] > randMax) { 
      randMax = random[l]; 
     } 
     /*prints the current power of 2, min, max, and avg 
      for each algorithm into a file*/ 
     StdOut.println("linear" + "," + n + "," + linMin + "," + linMax + "," + linAvg); 
     StdOut.println("binary" + "," + n + "," + binMin + "," + binMax + "," + binAvg); 
     StdOut.println("random" + "," + n + "," + randMin + "," + randMax + "," + randAvg); 
     } 
    } 
    } 
} 

Бинарный поиск, который я использую. Предоставляется для целей тестирования.

/*class containing binary search algorithm*/ 
public class BinarySearch { 
    /*conducts a binary search as specified by user*/ 
    public static int binarySearch(int queryValue, int[] list) { 
    int length = list.length; 
    /*last point of list*/ 
    int top = length-1;  
    /*first point of list*/ 
    int bottom = 0;  
    /*starting midpoint of list*/ 
    int mid = (int)Math.round((top + bottom)/2); 
    /*binary search*/ 
    do { 
     if(queryValue > list[mid]) { 
     bottom = mid; 
     mid = (int)Math.ceil((top + bottom)/2.0); 
     } 
     else { 
     top = mid; 
     mid = (int)Math.floor((top + bottom)/2.0); 
     } 
     if(queryValue == list[mid]) { 
     return mid; 
     } 
    } while (mid < top || mid > bottom); 
    /*returns -1 if user value not found*/ 
    return -1; 
    } 
} 

Линейный поиск, который я использую. Предоставляется для целей тестирования.

/*class containing linear search algorithm*/ 
public class LinearSearch { 
    public static int linearSearch(int queryValue, int[] list) { 
    int length = list.length; 
    /*conducts a linear search as specified by user*/ 
    for(int i = 0; i < length; i++) { 
     if((int)queryValue == (int)list[i]) { 
     return i; 
     } 
    } 
    /*return -1 if user value not found*/ 
    return -1; 
    } 
} 

Случайный поиск, который я использую. Предоставляется для целей тестирования.

import java.util.Random; 
/*class containing random search algorithm*/ 
public class RandomSearch { 
    public static int randomSearch(int queryValue, int[] list) { 
    /*conducts a random search as specified by user*/ 
    /*trys 10,000,000 random combinations searching 
     for user value*/ 
    int length = list.length; 
    for(int i=0; i < 10000000; i++) { 
     /*generates a random number from 0 to length*/ 
     int randomNum = (int)Math.floor(Math.random()*(length)); 
     if((int)queryValue == (int)list[randomNum]) { 
     return randomNum; 
     } 
    } 
    /*returns -2 if user value not found*/ 
    return -2; 
    } 
} 
+0

Что ошибка? –

+0

Ошибка компиляции. Программа запускается без распечатки каких-либо данных. Используя операторы печати, я смог выделить ошибку для цикла for, используя k. Бинарные, линейные и случайные массивы выводят 0 для каждого места в их соответствующих массивах. –

+0

Пожалуйста, добавьте эту информацию и все, что вы узнали, к вашему вопросу. –

ответ

0

Если это Java, вы хотите использовать System.out.println (....) не ваш Stdout ....

+0

У меня StdOut и StdIn сохранены в том же каталоге, поэтому они работают. –

+0

Обычными именами Java для входного потока являются System.out, а не StdOut. Я понятия не имею, что вы подразумеваете под «иметь StdOut saved ...» –

+0

Я использую программы из http://introcs.cs.princeton.edu/java/15inout/StdOut.java и http: // introcs. cs.princeton.edu/java/15inout/StdOut.java –

Смежные вопросы