键索引计数法 Java的实现与思路

tech2022-12-10  58

对于字符串的排序,不同与之前所学的值得排序,字符串的比较更为复杂,这里先学习一个基础算法叫做索引计数法,他是lfs和mfs的实现基础。

这个算法要求我们可以获取目标的键并按照这个键来排序。 此时我们有数据如下: 值 键 abc 2 cba 1 cca 3 cas 2 sas 1 sss 3 我们想要按照键调整数组的顺序 思路: 1.我们建立一个count数组用来记录每个键(键与count的索引一一对应)所对应元素的数量, 2.此时我们count数组中进行累加操作,那么此时count中记录的就是目标元素的起始索引了。 3.我们建立一个缓存string数组来存放排好序的元素 4,将排好序的元素回写到原数组中

代码:

/** * j建索引计数法 * */ public class suanfa11 { public static void main(String[] args) { myStr[] myStrs = {new myStr(2,"test1"),new myStr(1,"sss"),new myStr(3,"sss"),new myStr(2,"Ssss") ,new myStr(2,"Sssdasd"),new myStr(1,"Sdrsa"),new myStr(2,"Sdawaxz") }; //排序 indexSort(myStrs,4); //打印 for (myStr myStr : myStrs) { System.out.println(myStr.val+"--"+myStr.key()); } } public static void indexSort(myStr[] a,int r){ int[] count = new int[r+1]; for (myStr myStr : a) { count[myStr.key+1]++; } for (int i = 0; i < count.length-1; i++) { count[i+1]+=count[i]; } for (int i : count) { System.out.println(i); } myStr[] aux = new myStr[a.length]; for (int i = 0; i < a.length; i++) { aux[count[a[i].key]++] = a[i]; } for (int i = 0; i < a.length; i++) { a[i] = aux[i]; } } } class myStr{ int key; String val; public myStr(int key, String val) { this.key = key; this.val = val; } public int key() { return key; } public String val() { return val; } }
最新回复(0)