[英]how do i sort an array in ascending order, but by finding the greatest integer?
public static <T extends Comparable<? super T>> void modifiedSelectionSort(T[] a, int n) {
for( int index = 0; index < n - 1; index++) {
int indexOfGreatest = indexofGreatest(a, index, n -1);
T temp = a[index];
a[index] = a[indexOfGreatest];
a[indexOfGreatest] = temp;
}
}
private static <T extends Comparable<? super T>> int indexofGreatest(T[] a, int first, int last) {
T max = a[last];
int indexOfMax = last;
for (int index = last; index <= first; index-- ) {
if (a[index].compareTo(max) > 0) {
max = a[index];
indexOfMax = last;
}
}
return indexOfMax;
}
我想让这段代码在数组中找到最大的integer,放在数组的后面,然后再次搜索,找到第二大的integer并放在倒数第二位,以此类推
在第 12 行,“index”应该是 ">=" 到 "first" 而不是 "<=":
for (int index = last; index >= first; index-- ) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.