计数排序
需要有两个辅助条件
1.原数组中的最大值max
2.创建max+1长度的统计数组
话不多说,直接上代码
private int[] countSort1 (int[] nums) {
int n = nums.length;
if (n <= 1) {
return nums;
}
//获取原数组最大值
int max = Integer.MIN_VALUE;
for (int num : nums) {
max = Math.max(max, num);
}
int[] count = new int[max+1];
for (int num : nums) {
count[num]++;
}
int[] res = new int[n];
int index = 0;
for (int i = 0; i < count.length; i++) {
while (count[i] > 0) {
res[index++] = i;
count[i]--;
}
}
return res;
}
以上方法存在冗余空间的问题
优化方案一:
1.原数组中的最大值max 、min
2.创建max-min+1长度的统计数组count
3.count[num - min]++
4.在结果中赋值时 需要加上已经减去的min
private static int[] countSort2 (int[] nums) {
int n = nums.length;
if (n <= 1) {
return nums;
}
//获取原数组最大值
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int num : nums) {
max = Math.max(max, num);
min = Math.min(min, num);
}
int[] count = new int[max-min+1];
for (int num : nums) {
count[num - min]++;
}
int[] res = new int[n];
int index = 0;
for (int i = 0; i < count.length; i++) {
while (count[i] > 0) {
res[index++] = i+min;
count[i]--;
}
}
return res;
}
进阶优化
private static int[] countSort3 (int[] nums) {
int n = nums.length;
if (n <= 1) {
return nums;
}
//获取原数组最大值
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int num : nums) {
max = Math.max(max, num);
min = Math.min(min, num);
}
int[] count = new int[max-min+1];
for (int num : nums) {
count[num - min]++;
}
// 让计数数组count存储的元素值,
// 等于原始数组中相应整数的最终排序位置,
// 即计算原始数组中的每个数字在结果数组中处于的位置。
for (int i = 1; i < count.length;i++) {
count[i] += count[i-1];
}
int[] res = new int[n];
/**
* j = count[nums[i]-min]-1 就是res的下标
* res[j] = nums[i];
*/
for (int i = 0; i < n; i++) {
res[count[nums[i]-min]-1] = nums[i];
count[nums[i]-min]--;
}
return res;
}
进阶版的延伸之一
如果我们想要原始数组中的相同元素按照本来的顺序的排列,那该怎么处理呢?
{3,5,2,3,10,15} 要实现第二个 3 排在第一个3后面 那就只需要对上面写入结果集是进行处理,
/**
* 从后向前遍历
*/
for (int i = n - 1; i >= 0; i--) {
res[count[nums[i] - min] - 1] = nums[i];
count[nums[i] - min]--;
}
从前向后 是否可以达到同样的效果
public static int[] countSort5(int[] nums) {
// 找出数组A中的最大值、最小值
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int num : nums) {
max = Math.max(max, num);
min = Math.min(min, num);
}
// 初始化计数数组count
// 长度为最大值减最小值加1,再加1
int[] count = new int[(max-min+1)+1];
// 对计数数组各元素赋值,count[0]永远为0
for (int num : nums) {
// A中的元素要减去最小值再加上1,再作为新索引
count[num-min+1]++;
}
// 计数数组变形,新元素的值是前面元素累加之和的值
for (int i=1; i<count.length; i++) {
count[i] += count[i-1];
}
// 创建结果数组
int[] result = new int[nums.length];
// 遍历A中的元素,填充到结果数组中去,从前往后遍历
for (int j=0; j<nums.length; j++) {
// 如果后面遇到相同的元素,在前面元素的基础上往后排
// 如此就保证了原始数组中相同元素的原始排序
result[count[nums[j]-min]] = nums[j];
count[nums[j]-min]++;
}
return result;
}
本文来源于https://www.cnblogs.com/xiaochuan94/p/11198610.html