我正在尝试基数排序,我见过的一些算法有一个存储桶数组,它应该将多个整数保存到存储桶数组的一个索引中,下面是我引用的算法:

在一个索引中真的可以有多个整数吗?又是如何做到的呢?
或者有没有更简单的基数排序算法?
发布于 2012-11-30 09:33:13
是的,可以将多个int添加到一个数组中,但您需要有一个数组,其中每个项目都是一个Object而不是一个int。
例如..。
// the items to store in the array, which contain 3 ints
public class Bucket {
int number1 = -1;
int number2 = -1;
int number3 = -1;
public void addInt(int number){
if (number1 == -1){
number1 = number;
}
else if (number2 == -1){
number2 = number;
}
else if (number3 == -1){
number3 = number;
}
}
}
// the array, as used in other classes
Bucket[] bArray = new Bucket[6]; // 6 items in the array, where each item is a Bucket that contains 3 ints
// assigning ints into the array
bArray[2].addInt(56); // add the int '56' to the bucket at index '2' of the array
// You could also use other Array-like structures
ArrayList<Bucket> bList = new ArrayList<Bucket>();当然,如果存储桶中并不总是有<=3项,那么只需将bucket类更改为使用数组或List作为其变量,而不是使用单独的int。
你也可以使用多维数组...
// creating the buckets
int[][] buckets = new int[6][3];
// assigning ints into the array
bArray[2][0] = 56; // add the int '56' to the bucket at index '2' of the array, position '0'然而,如果你开始玩不同大小的桶,它会变得有点混乱,并且你需要做更多的错误检查来确保……
int。正是由于这些原因,我建议使用基于对象的数组而不是多维数组。
发布于 2012-11-30 09:34:23
两个案例创建存储桶
第一种情况实际上只是第二种情况的退化。
请注意,根据您对数字进行排序的顺序,有两种基数排序变体。
我也回答了这个问题的数据结构部分--不,你不能也不会在每个索引上存储多个值。相反,每个存储桶通常表示为数组的子序列。然后,每个存储桶由其开始的偏移量表示(结束可以是隐式的)。
发布于 2012-11-30 09:43:52
bucket本身就是一个int[] (或List或任何可以存储多个项的东西)。
你不能在一个索引中放入一个以上的东西。
int[] array = new array[6];
int value = array[5];如果存在多个int,则不再起作用。
最简单的方法可能是使用int[][]数组。现在,左边框中的每个索引都指向一个完整的数组。这些数组的长度也可以不同:
https://stackoverflow.com/questions/13637706
复制相似问题