链式基数排序

思路:使用链表存储数据,通过调整指针实现LSD(低关键字优先)算法进行排序。

package Lesson1;

import java.util.LinkedList;

class Card {
	private int type;
	private int point;

	public Card(int type, int point) {
		this.type = type;
		this.point = point;
	}
	public String toString() {
		return "(" + type + "," + point + ")";
	}

	public int getType() {
		return type;
	}
	public int getPoint() {
		return point;
	}

}

public class MyBase {

	public static void raidSort(LinkedList<Card> lst) {

		// low key matter
		LinkedList[] rd = new LinkedList[10];//10个空指针
		for (int i = 0; i < rd.length; i++) {
			rd[i] = new LinkedList<Card>();//初始化链表
		}

		while (lst.size() > 0) {//分组
			Card t = lst.remove();
			rd[t.getPoint() - 1].add(t);
		}

		for (int i = 0; i < rd.length; i++) {
			lst.addAll(rd[i]);//拼接
		}

		// high key matter
		LinkedList[] rd2 = new LinkedList[4];
		for (int i = 0; i < rd2.length; i++) {
			rd2[i] = new LinkedList();//初始化链表
		}

		while (lst.size() > 0) {//分组
			Card t = lst.remove();
			rd2[t.getType() - 1].add(t);
		}

		for (int i = 0; i < rd2.length; i++) {//拼接
			lst.addAll(rd2[i]);
		}

	}

	public static void main(String[] args) {
		LinkedList<Card> lst = new LinkedList<Card>();

		lst.add(new Card(2, 5));
		lst.add(new Card(3, 5));
		lst.add(new Card(2, 8));
		lst.add(new Card(1, 4));
		lst.add(new Card(1, 5));
		lst.add(new Card(4, 8));
		lst.add(new Card(2, 10));
		lst.add(new Card(3, 6));

		System.out.println(lst);//排序前

		raidSort(lst);//基数排序

		System.out.println(lst);//排序后

	}

}


你可能感兴趣的:(链式基数排序)