Создание метода сортировки с двойным выбором, и мой код отказывается проходить тесты, даже если нет ничего плохого - PullRequest
0 голосов
/ 08 декабря 2018

Это часть окончательного проекта из моей структуры данных и класса алгоритмов;Я проверял это снова и снова, многократно просматривал код, вплоть до , используя кости для симуляции случайно сгенерированных чисел и выполняя программу вручную. Я в полной растерянности!Похоже, ни один тест не скажет мне ничего о том, что происходит, за исключением того, что код перемещается в программе.На данный момент, я чувствую, что мне нужна другая пара более опытных глаз.Любая помощь приветствуется.

public void sort(T[] input) {
    System.out.println("~~~~~~~Begin Sort~~~~~~~"); //debug line
    System.out.println("Initial array as follows:"); //debug line
    for (int i = 0; i < input.length; ++i){
            System.out.print(input[i] + ", ");
        } //debug line
        System.out.print("\n\n"); //debug line
    int min; //Holds index of smallest item in array
    int max; //Holds index of largest item in array
    int lowBound = 0; //Holds index of the smallest index being explored;
                      //initialized as 0, the lowest possible index value
    int highBound = input.length - 1; //Holds index of the largest index
                                      //being explored; initialized as
                                      //highest index value in input[]
    T trader; //Holds value being traded

    while ((highBound - lowBound) > 0) {
        min = lowBound;  //Both of these are initialized and replaced with
        max = highBound; //the new highest and lowest values each time the
                         //while loop repeats
        System.out.println("Min and max set at " + min + " and " + max +
                " respectively"); //debug line
        for (int i = lowBound; i <= highBound; i++) {
            if (input[max].compareTo(input[i]) < 0) {
                max = i;
                System.out.println("new max found at " + i); //debug line
            } //Sets max to i (the new value) if the data at i is found to
              //be greater than the data at max
            if (input[min].compareTo(input[i]) > 0) {
                min = i;
                System.out.println("new min found at " + i); //debug line
            } //Sets min to i (the new value) if the data at i is found to
              //be less than the data at max
        } //Explores the region set by the bounds declared earlier
        if (!(min == highBound && max == lowBound)) {
            if (max != highBound){
                trader = input[highBound]; //Sets the trader to val @ highBound
                System.out.println("Trader is " + trader); //debug line
                input[highBound] = input[max]; //Sets val @ highBound to val @
                                               //max
                input[max] = trader; //Sets val @ max to val in the trader
                 System.out.println("HighBound is now " + input[highBound] +
                        " and max is now " + input[max]); //debug line
            } //Swaps the values at max and highBound if a change is necessary
            if (min != lowBound){
                trader = input[lowBound]; //Sets the trader to val @ lowBound
                System.out.println("Trader is " + trader); //debug line
                input[lowBound] = input[min]; //Sets val @ lowBound to val @ min
                input[min] = trader; //Sets val @ min to val in the trader 
                System.out.println("lowBound is now " + input[lowBound] +
                        " and min is now " + input[min]); //debug line
            } //Swaps the values at min and lowBound if a change is necessary
        } //Ensures min and max are not each other to prevent double-
          //swapping (allowing for two different swaps as the need arises)
        else {
            trader = input[min]; //Sets the trader to val @ lowBound
            System.out.println("Trader is " + trader); //debug line
            input[min] = input[max]; //Sets val @ lowBound to val @ min
            input[max] = trader; //Sets val @ min to val in the trader 
            System.out.println("lowBound is now " + input[lowBound] +
                    " and highBound is now " + input[highBound]); //debug line
        } //Swaps the values at highBound and lowBound if an outright switch
          //is necessary

        System.out.print("new array "); //debug line
        for (int i = 0; i < input.length; ++i){
            System.out.print(input[i] + ", ");
        } //debug line
        System.out.print("\n\n"); //debug line
        --highBound;
        ++lowBound;
    }
    System.out.println("~~~~~~~~End Sort~~~~~~~~~\n\n"); //debug line
}

1 Ответ

0 голосов
/ 09 декабря 2018

Я нашел проблему.В случае, когда минимальное или максимальное значение было найдено в HighBound или LowBound (соответственно), значения будут перепутаны, поскольку программа переместила то, что она считала максимальным или минимальным, в неправильную область.Восстановленный код находится ниже.

public void sort(T[] input) {
    System.out.println("~~~~~~~Begin Sort~~~~~~~"); //debug line
    System.out.println("Initial array as follows:"); //debug line
    for (int i = 0; i < input.length; ++i){
            System.out.print(input[i] + ", ");
        } //debug line
        System.out.print("\n\n"); //debug line
    int min; //Holds index of smallest item in array
    int max; //Holds index of largest item in array
    int lowBound = 0; //Holds index of the smallest index being explored;
                      //initialized as 0, the lowest possible index value
    int highBound = input.length - 1; //Holds index of the largest index
                                      //being explored; initialized as
                                      //highest index value in input[]
    T trader; //Holds value being traded

    while ((highBound - lowBound) > 0) {
        min = lowBound;  //Both of these are initialized and replaced with
        max = highBound; //the new highest and lowest values each time the
                         //while loop repeats
        System.out.println("\nMin and max set at " + min + " and " + max +
                " respectively"); //debug line
        System.out.println("Exploring region bound by " + lowBound + " and " + highBound);
        for (int i = lowBound; i <= highBound; i++) {
            if (input[max].compareTo(input[i]) < 0) {
                max = i;
                System.out.println("new max found at " + i); //debug line
            } //Sets max to i (the new value) if the data at i is found to
              //be greater than the data at max
            if (input[min].compareTo(input[i]) > 0) {
                min = i;
                System.out.println("new min found at " + i); //debug line
            } //Sets min to i (the new value) if the data at i is found to
              //be less than the data at max
        } //Explores the region set by the bounds declared earlier
        if (min == highBound && max == lowBound) {
            trader = input[min]; //Sets the trader to val @ lowBound
            System.out.println("Trader is " + trader); //debug line
            input[min] = input[max]; //Sets val @ lowBound to val @ min
            input[max] = trader; //Sets val @ min to val in the trader 
            System.out.println("lowBound is now " + input[lowBound] +
                    " and highBound is now " + input[highBound]); //debug line
        } //Ensures min and max are not each other to prevent double-
          //swapping (allowing for two different swaps as the need arises)
        else {
            if (min != lowBound){
                trader = input[lowBound]; //Sets the trader to val @ lowBound
                System.out.println("Trader is " + trader); //debug line
                input[lowBound] = input[min]; //Sets val @ lowBound to val @ min
                input[min] = trader; //Sets val @ min to val in the trader 
                System.out.println("lowBound is now " + input[lowBound] +
                        " and min is now " + input[min]); //debug line
                if (max == lowBound) {
                    max = min;
                }//ensures that the program doesn't get mixed up if the
                 //numbers get switched around
            } //Swaps the values at min and lowBound if a change is necessary
            if (max != highBound){
                trader = input[highBound]; //Sets the trader to val @ highBound
                System.out.println("Trader is " + trader); //debug line
                input[highBound] = input[max]; //Sets val @ highBound to val @
                                               //max
                input[max] = trader; //Sets val @ max to val in the trader
                 System.out.println("HighBound is now " + input[highBound] +
                        " and max is now " + input[max]); //debug line
                if (min == highBound) {
                    min = max;
                }//technically unnecessary, but symmetrical code is pretty
            }//Swaps the values at max and highBound if a change is necessary
        } //Swaps the values at highBound and lowBound if an outright switch
          //is necessary

        System.out.print("new array "); //debug line
        for (int i = 0; i < input.length; ++i){
            System.out.print(input[i] + ", ");
        } //debug line
        System.out.print("\n\n"); //debug line
        highBound--;
        lowBound++;
    }
    System.out.println("~~~~~~~~End Sort~~~~~~~~~\n\n"); //debug line
}

}

...