Nan*_*nto 5 java sorting algorithm selection-sort
我正在尝试将此选择排序从高到低编写,我不太清楚如何做到这一点.我对排序算法很陌生.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我试图改变它的原因是这里的选择排序贯穿数组的剩余部分,寻找最小值然后将其交换到前面.我想改变算法以便它也看起来对于剩余部分中的最大值,并将其交换到后面,以便它同时从前面和后面建立一个排序列表.
所有帮助将不胜感激:)
你只需要否定该compareTo方法
if(data[sweep].compareTo(data[minIndex]) > 0)
minIndex=sweep;
Run Code Online (Sandbox Code Playgroud)