如何反转选择排序
How to reverse 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);
}
}
之所以要改,是因为这里的选择排序是遍历数组的剩余部分,寻找最小值,然后换成front.I想改的算法使得它也从剩余部分中寻找最大值,并将其交换到后面,这样它就同时从前面和后面构建了一个排序列表。
所有帮助将不胜感激:)
你只需要否定compareTo
方法
if(data[sweep].compareTo(data[minIndex]) > 0)
minIndex=sweep;
A select 排序在每次迭代中找到最小的剩余项并放在正确的位置。相反,您想找到 最大的 剩余项。最简单的方法是翻转 selection 条件。而不是:
if (data[sweep].compareTo(data[minIndex]) < 0)
你应该使用:
if (data[sweep].compareTo(data[minIndex]) > 0)
我正在尝试按照从高到低的顺序编写此选择排序,但我不太确定该怎么做。我对排序算法还很陌生。
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);
}
}
之所以要改,是因为这里的选择排序是遍历数组的剩余部分,寻找最小值,然后换成front.I想改的算法使得它也从剩余部分中寻找最大值,并将其交换到后面,这样它就同时从前面和后面构建了一个排序列表。
所有帮助将不胜感激:)
你只需要否定compareTo
方法
if(data[sweep].compareTo(data[minIndex]) > 0)
minIndex=sweep;
A select 排序在每次迭代中找到最小的剩余项并放在正确的位置。相反,您想找到 最大的 剩余项。最简单的方法是翻转 selection 条件。而不是:
if (data[sweep].compareTo(data[minIndex]) < 0)
你应该使用:
if (data[sweep].compareTo(data[minIndex]) > 0)