переключатель не работает должным образом

1

Я не знаю, почему, но моя программа не работает так, как должна. quickSort() и mergeSort() кажутся выполняться два раза по каждому размеру массива. Это первый раз, когда я попытался использовать переключатель, поэтому я подозреваю, что он имеет какое-то отношение к этому.

целью этой программы является сравнение 4 методов сортировки.

public static void main(String[] args) throws Exception {
    //top line of excel spreadsheet
    String CSVString = "data size (100 times),bubble,insertion,merge,quick,,fastest,slowest\n";

    //how many elements in array to be sorted?
    int sizes[] = {10000, 20000, 100000, 200000, 1000000, 2000000};
    //used for min and max formulas in excel
    int rowNumber = 2;
    //sort each array with 4 sorting algorithms
    for (int size : sizes) {
        CSVString = sortRandomSet(size, CSVString, rowNumber);
        rowNumber++;
    }
    System.out.println("Writing data to benchmark.csv"
            + "\nNote that numbers higher than 99999 are not accurate");

    writeCSV(CSVString);
}//end main()


/**
 * *************************** sortRandomSet method
 * ************************** This method sorts an array with 4 sorting
 * methods (100 times each) Each sort is timed and added to a string for
 * outputting in CSV file CSVString is returned Last edited by Steve Pesce
 * 4/1/2014
 */
public static String sortRandomSet(int setSize, String CSVString, int rN) throws Exception {
    //this is the total time in seconds that it takes to sort the array 100 times
    double[] time = {0, 0, 0, 0};

    //these are used for calculating time[] time[x] = duration = end - start time
    long startTime;

    for (int j = 0; j < 4; j++) {
        //this for loop uses each sorting algorithm and times them each
        for (int k = 1; k <= 100; k++) {
            //new array and temp array of same size
            int[] randSet = new int[setSize];
            int[] temp = new int[randSet.length];
            //to show current progress
            System.out.print(k + "% done sorting " + setSize + " elements ");
            for (int i = 0; i < randSet.length; i++) {
                //fill array with random numbers
                randSet[i] = (int) (Math.random() * 10000);
            }
            startTime = System.nanoTime();

            //switch that executes in relation to j in this for loop
            switch (j) {
                case 0:
                    if (setSize < 100000)//this is where bubble takes too long
                    {
                        bubbleSort(randSet);
                        System.out.println("with bubble sort\n\n\n\n\n\n\n\n\n\n\n");
                        break;
                    } else {
                        time[j] = 9999;//set time to high value if sort skipped
                    }
                case 1:
                    if (setSize < 100000)//this is where insert takes too long
                    {
                        insertionSort(randSet);
                        System.out.println("with insertion sort\n\n\n\n\n\n\n\n\n\n\n");
                        break;
                    } else {
                        time[j] = 9999;//set time to high value if sort skipped
                    }
                case 2:
                    mergeSort(randSet, temp, 0, (randSet.length - 1));
                    System.out.println("with merge sort\n\n\n\n\n\n\n\n\n\n\n");
                    break;
                case 3:
                    quickSort(randSet, 0, randSet.length - 1);
                    System.out.println("with quick sort\n\n\n\n\n\n\n\n\n\n\n");
                    break;
                //calculate duration of sort and add to overall duration
            }
            time[j] = time[j] + ((System.nanoTime() - startTime) / 1000000000.0);
            //dont let time go over 9999
            if (time[j] > 9999) {
                time[j] = 9999;
            }
        }//end for
    }

    String maxMin;
    //used to put max and min functions in excel cells
    maxMin = ",,=min(b" + rN + ":e" + rN + "),=max(b" + rN + ":e" + rN + ")";

    //append new data to CSVString
    CSVString = (CSVString + setSize + "," + time[0] + "," + time[1] + "," + time[2] + ","
            + time[3] + maxMin + "\n");

    return CSVString;

}//end sortRandomSet()
  • 2
    Вы пропускаете операторы break в предложениях else ваших if в case 0 и case 1 или так работает ваш алгоритм?
  • 3
    Вы не нарушаете условия 'else'
Показать ещё 3 комментария
Теги:
sorting
switch-statement

1 ответ

1
Лучший ответ

Вот ваш код, упрощенный:

case 0:
    if (aBoolean)
    {
        break;
    } else {

    }
case 1:
    if (anotherBoolean)
    {
        break;
    } else {

    }
case 2:
    break;
case 3:
    break;

break; операторы для случаев 0 и 1 выполняются только в том случае, если aBoolean и anotherBoolean являются true. Когда один из них является ложным, оператор break не выполняется, и код внутри всего оператора switch начинает выполняться, начиная с этого оператора case.

Чтобы исправить это, поставьте операторы break прямо перед следующим случаем:

case 0:
    if (aBoolean)
    {

    } else {

    }
    break;
case 1:
    if (anotherBoolean)
    {

    } else {

    }
    break;
case 2:
    break;
case 3:
    break;

Ещё вопросы

Сообщество Overcoder
Наверх
Меню