技术排序原理和思路:按照数的低位到高位依次排序,
自己建造链表结构实现
package 算法;
public class RadisSort {
public static void main(String[] args) {
// 数组原始数据
int[] ary = new int[] { 135, 242, 192, 93, 345, 11, 24, 19 };
sort(ary);
}
// 排序
static void sort(int[] ary){
Struts head = new Struts();
int max = 0;//获取最大值
// 把数组转换为链表结构
head.setData(ary[0]);
Struts p, q;
p = head;
for (int i = 1; i < ary.length; i++) {
if(max<ary[i]){
max=ary[i];
}
q = new Struts();
q.setData(ary[i]);
p.setNext(q);
p = q;
}
int times = 0;//获取最大值位数
while(max>0){
max = max/10;
times++;
}
for (int i = 1; i <= times; i++) {
head = radis(head, i);
}
out(head);
}
/**
* 链表输出
*
* @param radis
*/
static void out(Struts radis) {
while (radis != null) {
System.out.print(radis.getData() + " ");
radis = radis.getNext();
}
System.out.println();
}
/**
* 对链表按找位进行排序
*
* @param head
* @param wei
*/
static Struts radis(Struts head, int wei) {
// 0-9链表的头
Struts[] HNB = new Struts[10];
// 0~9链表的尾
Struts[] HNE = new Struts[10];
Struts headtemp = null;
;
// 设置取余的位数
int jishu1 = 1, jishu2, j = 0;
boolean bj = true;
while (--wei > 0) {
jishu1 *= 10;
}
jishu2 = jishu1 * 10;
Struts p;
p = head;
while (p != null) {
int index = (p.getData() % jishu2) / jishu1;
// 如果链表为空直接加入
if (HNB[index] == null) {
// 头为p,尾巴也为p;
HNB[index] = p;
HNE[index] = p;
} else {
// 设置新的尾巴。
HNE[index].setNext(p);
HNE[index] = p;
}
p = p.getNext();
}
for (int i = 0; i < HNB.length; i++) {
if (HNB[i] != null) {
// 第一个非空的一位数连表
if (bj) {
headtemp = HNB[i];
bj = false;
j = i;
} else {
// 非第一位比奥之间进行链接
HNE[j].setNext(HNB[i]);
j = i;
}
}
}
HNE[j].setNext(null);
return headtemp;
}
}
/**
* 结构题类
* @author Administrator
*
*/
class Struts {
private int data;
private Struts next;
Struts() {
next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Struts getNext() {
return next;
}
public void setNext(Struts next) {
this.next = next;
}
}
数组结构实现
package 算法;
import java.util.ArrayList;
import java.util.List;
public class BasicSort {
public void sort(int [] array){
int max = 0;//获取最大值
for(int i = 0;i<array.length;i++){
if(max<array[i]){
max = array[i];
}
}
int times = 0;//获取最大值位数
while(max>0){
max = max/10;
times++;
}
List<ArrayList> queue = new ArrayList<ArrayList>();//多维数组
for(int i = 0;i<10;i++){
ArrayList q = new ArrayList<>();
queue.add(q);
}
for(int i = 0;i<times;i++){
for(int j = 0;j<array.length;j++){
//获取对应的位的值(i为0是各位,1是10位,2是百位)
int x = array[j]%(int)Math.pow(10, i+1)/(int)Math.pow(10, i);
ArrayList q = queue.get(x);
q.add(array[j]);//把元素添加进对应下标数组
}
//开始收集
int count = 0;
for(int j = 0;j<10;j++){
while(queue.get(j).size()>0){
ArrayList<Integer> q = queue.get(j);//拿到每一个数组
array[count] = q.get(0);
q.remove(0);
count++;
}
}
}
}
public static void main(String[] args){
BasicSort basicSort = new BasicSort();
int [] a = {136,2,6,8,9,2,8,11,23,56,34,90,89,29,145,209,320,78,3};
basicSort.sort(a);
for(int n:a){
System.out.print(" "+n);
}
}
}