码迷,mamicode.com
首页 > 其他好文 > 详细

BucketSort Implementation

时间:2020-02-18 09:14:49      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:algo   ping   dex   put   less   lease   cat   math   wan   

Imagine you have an array like this (note that the array has duplicates, and includes 0 and k):

a = [ 4, 64, 200, 42, 56, 22, 1, 64, 0, 161, 200, 0, 42 ]

 

What you know about this array is

Values are integers

Values are non-negative and less than some number, for example:

0 <= value <= k, where k is an integer


To start, can you please write some code to sort this array using any algorithm you want and not using the library functions. Let’s assume there are no space/time requirements. This part of the coding interview is not about the algorithms, our goal is to write some code and get it running.

 

 1 public void bucketSort(int[] arr) {
 2         if (arr == null || arr.length < 1) return;
 3         Map<Integer, Integer> itemToCountMapping = new HashMap<>();
 4         int min = arr[0];
 5         int max = arr[0];
 6 
 7         for (int value : arr) {
 8             min = Math.min(min, value);
 9             max = Math.max(max, value);
10             itemToCountMapping.put(value, itemToCountMapping.getOrDefault(value, 0) + 1);
11         }
12         
13         int index = 0;
14         for (int i = min; i <= max; i++) {
15             int count = itemToCountMapping.getOrDefault(i, 0);
16             for (int j = 1; j <= count; j++) {
17                 arr[index] = i;
18                 index++;
19             }
20         }
21     }

 

BucketSort Implementation

标签:algo   ping   dex   put   less   lease   cat   math   wan   

原文地址:https://www.cnblogs.com/beiyeqingteng/p/12324686.html

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