排序算法类的模板:
public class Example
{
public static void sort(Comparable[] a)
{ /* */ }
#对元素进行比较
private static boolean less(Comparable v,Comparable w)
{ return v.compareTo(w)<0 }
# 将元素交换位置
private static void exch(Comparable[] a,int i,int j)
{ Comparable t=a[i];a[i]=a[j];a[j]=t }
#在单行中打印数组
private static void show(Comparable[] a)
{
for (int i=0;i<a.length;i++)
StdOut.print(a[i] + " ");
StdOut.printIn();
}
#测试数组元素是否有序
public static boolean isSorted(Comparable[] a)
{for (int i=1; i<a.length;i++)
if (less(a[i],a[i-1])) return false
return true;
}
#从标准输入读取字符串,将他们排序并输出
public static void main(String[] args)
{
String[] a = In.readString();
Sort(a);
assert isSorted(a);
show(a)
}
}
定义一个可排序的数据类型
创建自己的数据类型时,我们只要实现Comparable接口就能保证用例代码可以将其排序。要做到这点,需要实现一个compareTo() 方法来定义目标类型对象的自然次序
CASE1:
创建一个可排序的数据类型
package rankCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class dateRank implements Comparable<dateRank> {
private static final Logger logger = LoggerFactory.getLogger(dateRank.class);
private final int day;
private final int month;
private final int year;
public dateRank(int d, int m, int y) {
day = d;
month = m;
year = y;
}
public int getDay() {return day;}
public int getMonth() {return month;}
public int getYear() {return year;}
public int compareTo(dateRank o) {
if (this.year > o.year) { return 1; }
if (this.year < o.year) { return -1; }
if (this.month > o.month) { return 1; }
if (this.month < o.month) { return -1; }
if (this.day > o.day) { return 1; }
if (this.day < o.day) { return -1; }
return 0;
}
@Override
public String toString() {
return month + "/" + day + "/" + year;
}
}
测试用例:
import static java.util.Arrays.sort;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rankCore.dateRank;
public class dateRankTest {
private static final Logger logger = LoggerFactory.getLogger(dateRankTest.class);
public static void main(String args[]) {
dateRank[] dateranks = new dateRank[2];
dateranks[0] = new dateRank(15, 4, 1991);
dateranks[1] = new dateRank(05, 4, 1991);
sort(dateranks);
for(int i=0; i<dateranks.length;i++)
//System.out.println(dateranks[i].toString());
logger.info(dateranks[i].toString());
}
}
网友评论