LSD:低关键字优先;链式基数排序;lst.remove();取出和删除表头元素

来源:互联网 发布:淘宝的销量可以刷吗 编辑:程序博客网 时间:2024/06/05 06:59

按照关键字为依据进行分组的排序方法,有MSD和LSD两种方案。其中,LSD方案很特别,适合多关键字,只通过分配与收集即可完成排序。

LSD首先的分组的组位置就已经排好了,再一个先从低关键字开始,最后高关键字将是主导作用;可以拆分关键字

使用LSD方案,反复进行分配和收集的排序方法。通过链表的使用降低了排序期间对内存的消耗。

import java.util.LinkedList;
import com.sun.org.apache.regexp.internal.REUtil;

class Card{
private int type;//花色
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
private int point;//值
public Card(int type,int point) {
this.type=type;
this.point=point;
}
public String toString() {
return "("+type+","+point+")";
}
}
public class CardMulKeySort {
public static enum typeEnum {
red,block,plum_blossom,spade;


public static int valueOf(typeEnum x) {
for (int i = 0; i < typeEnum.values().length; i++) {
if (x==typeEnum.values()[i]) {
return i;
}

}
return -1;
}
}
/**
* 排序,
有种静态方法static{内容}是在类实例化时就生成
*/
@SuppressWarnings("unchecked")
static void raidSort(LinkedList<Card> lst){
//对低关键字进行分组
LinkedList[] rd=new LinkedList[10];//假设值从1到10
for(int i=0;i<rd.length;i++)rd[i]=new LinkedList();//每个值具体有多少个不确定
//吧lst中元素拆下来放入对应的组中
while (lst.size()>0) {
Card t=lst.remove();//删除的表头元素
rd[t.getPoint()-1].add(t);//添加到该组的链表尾部,point从1到10,数组从0到9
}

//收集
for (int i = 0; i < rd.length; i++) {
lst.addAll(rd[i]);
}
//对高关键字进行分组
rd=new LinkedList[4];
for(int i=0;i<rd.length;i++)rd[i]=new LinkedList();
while (lst.size()>0) {
Card t=lst.remove();//删除的表头元素
rd[t.getType()].add(t);//添加到该组的链表尾部,point从1到10,数组从0到9
}
//收集
for (int i = 0; i < rd.length; i++) {
lst.addAll(rd[i]);
}
}
/**
* @param args
*/
public static void main(String[] args) {
LinkedList<Card> lst=new LinkedList<Card>();
lst.add(new Card(typeEnum.valueOf(typeEnum.block), 5));
lst.add(new Card(typeEnum.valueOf(typeEnum.red), 5));
lst.add(new Card(typeEnum.valueOf(typeEnum.block), 7));
lst.add(new Card(typeEnum.valueOf(typeEnum.block),3));
lst.add(new Card(typeEnum.valueOf(typeEnum.block), 5));
lst.add(new Card(typeEnum.valueOf(typeEnum.spade), 5));
lst.add(new Card(typeEnum.valueOf(typeEnum.spade), 9));
lst.add(new Card(typeEnum.valueOf(typeEnum.red), 5));
lst.add(new Card(typeEnum.valueOf(typeEnum.plum_blossom), 6));
System.out.println(lst);
raidSort(lst);
System.out.println(lst);
}


}

14 0