java使用比较器和交换功能排序 [英] java sorting with comparator and swap function
问题描述
我需要使用自定义比较器和交换功能对功能进行排序.我可以自己写一个,但我想知道其他人是否还没有写过. Java运行时包含许多专门的排序功能,用于对原始类型,对象等的数组进行排序,但是它们都不使用交换功能作为参数. Google搜索也没有发现有用的东西.
I need to sorting function with custom comparator and swap function. I can write one myself, but I'm wondering if someone else didn't already do it. Java runtime contains many specialized sorting function for sorting arrays of primitive types, objects etc., but none of them take swap function as an argument. Google search also didn't find anything useful.
public interface IntComparator
{
int compare(int a, int b);
}
public interface IntSwap
{
void swap(int a, int b);
}
public static void sort(IntComparator compFn, IntSwap swapFn, int off, int len);
推荐答案
这就是我想要的.它基于Java运行时算法对整数进行排序.通过正确实现Sortable接口,它几乎可以对任何东西进行排序.
Here is what I was looking for. It's based on java runtime algorithm for sorting integers. With proper implementation of Sortable interface, it can sort just about anything.
public class Sort {
public static void sort(Sortable sortable, int off, int len) {
// Insertion sort on smallest arrays
if (len < 7) {
for (int i = off; i < len + off; i++) {
for (int j = i; j > off && sortable.compare(j - 1, j) > 0; j--) {
sortable.swap(j, j - 1);
}
}
return;
}
}
这篇关于java使用比较器和交换功能排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!