Reverse SelectionSort 对数组进行排序

Reverse SelectionSort to sort array

我这里的选择排序遍历数组的剩余部分,寻找最小值,然后将其交换到front.I想改变算法,让它也在数组中寻找最大值剩下的部分,并交换到后面,这样就同时从前面和后面构建了一个排序列表。

public  void selectionSort(String[ ] data){
    // for each position, from 0 up, find the next smallest item 
    // and swap it into place
    for (int place=0; place<data.length-1; place++){
        int minIndex = place;
        for (int sweep=place+1; sweep<data.length; sweep++){
            if (data[sweep].compareTo(data[minIndex]) < 0)
                minIndex=sweep;
        }
        swap(data, place, minIndex);
    }
}

我有另一种方法可以检查数组是否已排序,因此解决方案必须经过那个

public boolean testSorted(String[] data) {
    for (int i=1; i<data.length; i++){
        if (data[i].compareTo(data[i-1]) < 0)
            return false;
    }
    return true;
}

任何帮助将不胜感激,我已经为此工作了几个小时。我对此很陌生,我真的很想得到它。谢谢

这是我试过的:

public  void selectionSort2(String[ ] data){
    // for each position, from 0 up, find the next smallest item 
    // and swap it into place
    for (int place=0; place<data.length-1; place++){
        int minIndex = place;
        for (int sweep=place+1; sweep<data.length; sweep++){
            if (data[sweep].compareTo(data[minIndex]) > 0)
                minIndex=sweep;
        }
        swap(data, place, minIndex);
    }
}

你只需要改一下,它就会倒序排列:

在方法中selectionSort()

if (data[sweep].compareTo(data[minIndex]) > 0)

并在方法中 testSorted()

if (data[i].compareTo(data[i-1]) > 0)

但是如果你需要改变顺序,它必须从数组的后面开始排序,它看起来像:

    public static void selectionSort(String[ ] data){
    // for each position, from 0 up, find the next smallest item
    // and swap it into place
    for(int place=data.length-1; place >= 1; place--){
        int maxIndex= place;
        for(int sweep = place-1; sweep >= 0; sweep--){
            if(data[sweep].compareTo(data[maxIndex]) > 0){
                maxIndex = sweep;
            }
        }
        swap(data, place, maxIndex);
    }