Проблема с реализацией двунаправленной сортировки выбором

Я пытаюсь реализовать сортировку с двунаправленным выбором (сортировка с двойным выбором). Сортировка с двойным выбором находит как самый маленький, так и самый большой элемент во время сканирования и меняет местами самый маленький элемент на первую позицию, а самый большой — на последнюю позицию. Затем алгоритм продолжает просмотр всех элементов между первым и последним.

Я могу получить логику, необходимую для выполнения задачи. Но я думаю, что делаю что-то не так, сравнивая переменные или, возможно, правильно реализуя сопоставимость.

public void sort(T[] input) {

for(int i=0; i<input.length -1; i++){

    int min = i;
    int max = i;

    for(int j=i+1; j<input.length; j++){

        if(input[min].compareTo((input[j])) > 0  )
        {
            min = j;
            T swap = input[min];
            input[min] = input[i];
            input[i] = swap;

        }
    }

    for(int k=i+1; k<input.length; k++){

        if(input[max].compareTo((input[k])) < 0  )
        {
            max = k;
            T swap = input[max];
            input[max] = input[i];
            input[i] = swap;

        }
    }


}


}

///// Тестовый файл

   /** Returns true if the input array is ordered (every element ≤ 
    * the following one.)
    * 
    * @param data Array to check
     * @return     True if array is ordered
     */
    boolean isOrdered(Integer[] data) {
    for(int i = 0; i < data.length - 1; ++i)
        if(data[i] > data[i+1])
            return false;

    return true;
}

/** Counts the number of times x occurs in the array in.
 * 
 * @param in Array
 * @param x  Element to count
 * @return   Count of x's in the array
 */
int countElement(Integer[] in, Integer x) {
    int c = 0;
    for(int i : in) 
        if(i == x)
            c++;

    return c;
}

/** Returns true if both arrays contain the same elements, 
 * disregarding order (i.e., is one a permutation of the other).
 * @param in  Unsorted array
 * @param out Potentially-sorted array to check
 * @return    True if out is a permutation of in
 */
boolean sameElements(Integer[] in, Integer[] out) {
    for(Integer i : in)
        if(countElement(in,i) != countElement(out,i))
            return false;

    return true;
}

/** Creates an array of the given size filled with random values.
 * 
 * @param size Size of the resulting array
 * @return     Array of random values
 */
Integer[] randomArray(int size) {
    Integer[] arr = new Integer[size];
    for(int i = 0; i < size; ++i)
        arr[i] = Math.round((float)Math.random() * Integer.MAX_VALUE);

    return arr;
}

/** Tests the DoubleSelectionSort dss against the unsorted data.
 * 
 * @param dss  Sorter to use
 * @param data Array to sort and check
 */
void testSort(DoubleSelectionSort dss, Integer[] data) {
    Integer[] sorted = Arrays.copyOf(data, data.length);
    dss.sort(sorted);        

    assertTrue("Result of sort is not sorted in order", isOrdered(sorted));
    assertTrue("Result of sort has different elements from input", sameElements(data, sorted));
}

@Test
public void testSort() {
    System.out.println("sort");
    DoubleSelectionSort<Integer> dss = new DoubleSelectionSort<>();

    // Test on arrays size 0 to 100
    for(int i = 0; i <= 100; ++i)
        testSort(dss, randomArray(i));               
  }

}

testSort Failed: результат сортировки не отсортирован по порядку


person Meet Yeole    schedule 19.09.2019    source источник
comment
Ваш код сбивает с толку. Прокомментируйте код (опишите метод сортировки), чтобы было понятно.   -  person m-2127    schedule 19.09.2019
comment
nElems всегда равно 0. вы никогда не обновляете его, поэтому цикл никогда не запускается   -  person mangusta    schedule 19.09.2019
comment
Я обновил свой код в соответствии с моим растущим пониманием, но все еще имею ту же ошибку.   -  person Meet Yeole    schedule 19.09.2019


Ответы (1)


Кажется, вы используете неправильные условия в логике сортировки Selection Sort. Я привел здесь пример функции Selection Sort с типом generic. Пожалуйста, взгляните на это:

public static <E extends Comparable<E>> void selectionSort(E[] list)
{
    for(int i=0; i<list.length -1; i++)
    {
        int iSmall = i;

        for(int j=i+1; j<list.length; j++)
        {
            if(list[iSmall].compareTo((list[j])) > 0  )
            {
                iSmall = j;
            }
        }
        E iSwap = list[iSmall];
        list[iSmall] = list[i];
        list[i] = iSwap;

    }
}
person Krishna Vyas    schedule 19.09.2019
comment
О, я понял. Это работает. Точно так же я пытался найти максимальное число и поменять его местами. Я обновил свой пост. Это должно работать, но я не знаю, что не так. Может быть, вы можете помочь. - person Meet Yeole; 20.09.2019