码迷,mamicode.com
首页 > 编程语言 > 详细

计数排序

时间:2020-11-27 11:52:06      阅读:22      评论:0      收藏:0      [点我收藏+]

标签:dex   code   cache   imp   rgs   next   exti   main   ati   

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); }); } }

计数排序

标签:dex   code   cache   imp   rgs   next   exti   main   ati   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!