[英]How to use selection sort with comparator in java?
这里的帮助将不胜感激。 我很困。 我需要做的是我必须使用选择排序算法对一个数组列表进行排序,但是数组列表中的每个对象都有多个索引。 这必须在Java中完成。
例如:
public class a {
private int number;
private String letter;
public a(int n, String l)
{
number = n;
letter = l;
}
}
public class SortingArrays {
private ArrayList<a> myarray;
private Comparator<a> sortByNumber;
private Comparator<a> sortByLetter;
public FootballPlayerData() {
myarray = new ArrayList<a>();
getmyarray().add(new a(2, "A"));
getmyarray().add(new a(7, "J"));
//COMPARATORs//
sortByNumber = new Comparator<a>() {
@Override
public int compare(a o1, a o2)
{
if (o1.number < (o2.number)) {
return -1;
}
if (o1.number == (o2.number)) {
return 0;
}
return 1;
}
};
sortByLetter = new Comparator<a>() {
@Override
public int compare(a o1, a o2)
{
return o1.letter.compareTo(o2.letter);
}
};
public void selectionSortbyNumber
{
???
}
public void selectionSortbyLetter
{
???
}
}
那么,如何在Java中创建选择排序(必须是选择排序),从而根据对象内的不同元素对arraylist进行排序? 我已经把比较器部分放下了,但是我不知道如何将它与选择排序结合在一起。
来自https://en.wikipedia.org/wiki/Selection_sort的来源:
/* a[0] to a[n-1] is the array to sort */
int i,j;
int n;
/* advance the position through the entire array */
/* (could do j < n-1 because single element is also min element) */
int iMin;
for (j = 0; j < n-1; j++) {
/* find the min element in the unsorted a[j .. n-1] */
/* assume the min is the first element */
iMin = j;
/* test against elements after j to find the smallest */
for (i = j+1; i < n; i++) {
/* if this element is less, then it is the new minimum */
if (a[i] < a[iMin]) {
/* found new minimum; remember its index */
iMin = i;
}
}
}
if (iMin != j) {
swap(a[j], a[iMin]);
}
方法swap()
只是切换数组中的值。
您的工作将是用列表交换数组。 :P但这并不难,因为您可以通过索引get(int index)
方法访问列表值。
Comparator
实现通常用于比较两个元素,如果第一个元素小于第二个,则返回-1
(或任何负数);如果相等,则返回0
如果第一个元素小于1,则返回1
(或任何正数)。元素大于第二个元素。 这可用于比较两个元素,以查看一个元素是否大于,小于或等于另一个。
在选择排序的上下文中,可以使用提供的比较器来确定列表中未排序部分中的哪个值是最小值。 选择排序的一般算法如下:
for i from 0 to array.length:
current_minimum_index = i
for j from i + 1 to array.length:
if array at j is less than array at current_minimum_index:
current_minimum_index = j
swap array at current_minimum_index with array at i
可以使用Comparator
实现if array at j is less than array at current_minimum_index
的if array at j is less than array at current_minimum_index
。 例如,给定提供的名为array
ArrayList
,对名为comparator
的Comparator
对象的调用将为:
if (comparator.compare(array.get(j), array.get(current_minimum_index))) < 0)
我不想为您提供完整的答案,因为这不会帮助您学习选择排序,但是排序的方法签名类似于以下内容:
public <T> void selectionSort(ArrayList<T> array, Comparator<T> comparator) {
// for i from 0 to array.size():
// currentMinIndex = i
// for j from i + 1 to array.size():
if (comparator.compare(array.get(j), array.get(currentMinIndex))) < 0) {
// currentMinIndex = j
}
// swap array at currentMinIndex with array at i
}
您对此方法的调用将类似于以下之一:
selectionSort(myarray, sortByNumber);
selectionSort(myarray, sortByLetter);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.