计数排序
[编程语言教程]

import java.util.Arrays;
import java.util.Random;

public class CountSort {

static class Item {
int index;
int num;
}

private static void sort(Item[] items, int bound) {

int n = items.length;

int[] count = new int[bound];
int[] sum = new int[bound];

Item[] cache = Arrays.copyOf(items, n);

for (int i = 0; i < n; ++ i) {
count[items[i].num] ++;
}

sum[0] = count[0];

for (int i = 1; i < bound; ++ i) {
sum[i] = sum[i - 1] + count[i];
}

for (int i = n - 1; i >= 0; -- i) {
items[-- sum[cache[i].num]] = cache[i];
}
}

public static void main(String[] args) {

int n = 10;

Random random = new Random();

Item[] items = new Item[n];

for (int i = 0; i < n; ++ i) {
items[i] = new Item();
items[i].index = i;
items[i].num = random.nextInt(5);
}

Arrays.stream(items).forEach(item -> {
System.out.println(item.index + "->" + item.num);
});
sort(items, 5);
System.out.println("排序后");
Arrays.stream(items).forEach(item -> {
System.out.println(item.index + "->" + item.num);
});
}
}

计数排序

原文地址:https://blog.51cto.com/tianyiya/2553857

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 计数排序